移动到不同模块的资源定义是否会使 'terraform apply' 删除和重新创建这些资源?

Jun*_*Jun 5 terraform

我创建了一些带有 main.tf 的虚拟机,terraform 生成了一个 cluster.tfstate 文件。

现在因为重构,我把VM资源定义移到一个模块中,并在main.tf中引用这个模块。当我运行时terraform apply --state=./cluster.tfstate,terraform 会破坏并重新创建这些虚拟机吗?

我希望它不会。我的理解正确吗?

Eri*_*son 9

让我们使用aws_instance 文档中给出的示例来尝试一下:

\n\n
# Create a new instance of the latest Ubuntu 14.04 on an\n# t2.micro node with an AWS Tag naming it "HelloWorld"\nprovider "aws" {\n  region = "us-west-2"\n}\n\ndata "aws_ami" "ubuntu" {\n  most_recent = true\n\n  filter {\n    name   = "name"\n    values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]\n  }\n\n  filter {\n    name   = "virtualization-type"\n    values = ["hvm"]\n  }\n\n  owners = ["099720109477"] # Canonical\n}\n\nresource "aws_instance" "web" {\n  ami           = "${data.aws_ami.ubuntu.id}"\n  instance_type = "t2.micro"\n\n  tags {\n    Name = "HelloWorld"\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果我们terraform apply这样做,我们会得到一个在 Terraform 中引用的实例aws_instance.web

\n\n

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

\n\n

如果我们将此定义移至模块ubuntu_instance,则目录结构可能如下所示,其中包含上述代码instance.tf

\n\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.tf\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 ubuntu_instance\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 instance.tf\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在您打算创建与以前相同的实例,但 Terraform 现在在内部命名该资源module.ubuntu_instance.aws_instance.web

\n\n

如果您尝试应用此功能,您将得到以下结果:

\n\n

Plan: 1 to add, 0 to change, 1 to destroy.

\n\n

发生这种情况的原因是 Terraform 不知道新旧代码引用同一个实例。当您重构模块时,您正在删除资源,因此 Terraform 会删除该资源。

\n\n

Terraform 将您的代码映射到状态文件中的实际资源。当您创建实例时,您只能aws_instance通过状态文件知道该实例映射到您的实例。因此,正确的方法(如Jun所提到的)是重构您的代码,然后告诉 Terraform 将映射从 移动到真实实例 然后aws_instance.webmodule.ubuntu_instance.aws_instance.web您应用时,Terraform 将保留该实例,因为它与您的代码所说的相匹配。Jun 链接的文章对此进行了很好的讨论

\n