gpt4 book ai didi

amazon-web-services - Terraform 上的 AWS - 如何避免 'forces new resource'

转载 作者:行者123 更新时间:2023-12-02 07:17:14 25 4
gpt4 key购买 nike

我正在使用 Terraform 来启动我的云环境。

似乎即使是很小的配置更改也会影响幕后的许多资源。

例如,在我创建 AWS 实例的情况下 - 一个小的更改将导致所有实例的自动生成:

-/+ aws_instance.DC (new resource required)
id: "i-075deb0aaa57c2d" => <computed> (forces new resource) <----- How can we avoid that?
ami: "ami-01e306baaaa0a6f65" => "ami-01e306baaaa0a6f65"
arn: "arn:aws:ec2:ap-southeast-2:857671114786:instance/i-075deb0aaa57c2d" => <computed>
associate_public_ip_address: "false" => <computed>
availability_zone: "ap-southeast-2a" => <computed>
.
.

我的问题特别与作为提供商的 AWS 相关:
我们如何避免每次都破坏/创建资源?

也许是 Terraform 中的相关标志?

相关主题:

Terraform > ipv6_address_count: "" => "0" (forces new resource)

terraform > forces new resource on security group

编辑:

深入了解计划输出,其中一项资源似乎发生了变化:
  security_groups.#: "0" => "1" (forces new resource)
security_groups.837544107: "" => "sg-0892062659392afa9" (forces new resource)

从如何避免重新创造的角度来看,问题仍然是相关的。

最佳答案

如果在修改资源以匹配新配置时没有明确的升级路径,Terraform 资源只会强制使用新资源。这是通过在参数上设置 ForceNew: true 标志在提供程序级别完成的。

ami parameter on the aws_instance resource 显示了一个示例:

        Schema: map[string]*schema.Schema{
"ami": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

这告诉 Terraform,如果 ami 参数发生更改,则不应尝试执行更新,而是销毁资源并创建新资源。

您可以使用 create_before_destroy lifecycle configuration 块覆盖销毁然后创建行为:
resource "aws_instance" "example" {
# ...

lifecycle {
create_before_destroy = true
}
}

如果您更改了 ami 或其他一些无法更新的参数,Terraform 将创建一个新实例,然后销毁旧实例。

您如何处理资源的零停机升级可能很棘手,这在很大程度上取决于资源是什么以及您如何处理它。在 official blog 中有更多关于它的信息。

在您非常具体的用例中,它是 security_groups 改变了这一点,在 aws_instance resource docs 中提到:

NOTE: If you are creating Instances in a VPC, use vpc_security_group_ids instead.



这是因为 Terraform 的 AWS 提供商和 Terraform 使用的 EC2 API 向后兼容早于 VPC 的旧 EC2 Classic AWS 账户。使用这些帐户,您可以在 VPC 之外创建实例,但在创建实例后您无法更改实例的安全组。如果您想更改实例的入口/导出,您需要在已附加到实例的组内工作。借助基于VPC的实例,AWS允许用户修改实例安全组而无需替换实例,因此提供了在API中指定此实例的另一种方式。

如果您转而使用 vpc_security_group_ids 而不是 security_groups,那么您将能够在不替换实例的情况下修改它们。

关于amazon-web-services - Terraform 上的 AWS - 如何避免 'forces new resource',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59309243/

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