gpt4 book ai didi

terraform - 资源定义移动到不同的模块会导致 'terraform apply' 删除并重新创建这些资源吗?

转载 作者:行者123 更新时间:2023-12-03 19:35:30 25 4
gpt4 key购买 nike

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

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

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

最佳答案

让我们用 the aws_instance documentation 中给出的例子来试试这个。 :

# Create a new instance of the latest Ubuntu 14.04 on an
# t2.micro node with an AWS Tag naming it "HelloWorld"
provider "aws" {
region = "us-west-2"
}

data "aws_ami" "ubuntu" {
most_recent = true

filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
}

filter {
name = "virtualization-type"
values = ["hvm"]
}

owners = ["099720109477"] # Canonical
}

resource "aws_instance" "web" {
ami = "${data.aws_ami.ubuntu.id}"
instance_type = "t2.micro"

tags {
Name = "HelloWorld"
}
}

如果我们 terraform apply这样,我们得到一个在 Terraform 中被引用为 aws_instance.web 的实例:
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
如果我们将此定义移至模块 ubuntu_instance ,目录结构可能看起来像上面的代码 instance.tf :
.
├── main.tf
└── ubuntu_instance
└── instance.tf

现在您打算创建与以前相同的实例,但在内部 Terraform 现在将此资源命名为 module.ubuntu_instance.aws_instance.web
如果您尝试应用此功能,您将获得以下信息:
Plan: 1 to add, 0 to change, 1 to destroy.
发生这种情况的原因是 Terraform 不知道新旧代码引用同一个实例。在模块中重构时,您正在删除资源,因此 Terraform 会删除该资源。

Terraform 将您的代码映射到状态文件中的真实资源。创建实例时,您只能知道该实例映射到您的 aws_instance。因为状态文件。因此,正确的方法(如 Jun 所述)是重构您的代码,然后告诉 Terraform 将映射从 aws_instance.web 移动到真实实例至 module.ubuntu_instance.aws_instance.web然后,当您申请时,Terraform 将不理会该实例,因为它与您的代码所说的相匹配。 The article Jun linked to is a good discussion of this .

关于terraform - 资源定义移动到不同的模块会导致 'terraform apply' 删除并重新创建这些资源吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49626673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com