Terraform - 在修改仍然存在依赖组件的单个 AWS 组件时抛出错误

Terraform - throws error on modifying individual AWS components where the dependent ones are still present

我仍然是 Terraform 的初学者。我有一个场景,假设只需要重新创建一个 AWS 组件但依赖于不需要任何更改的其他组件,例如如果存在 AutoScaling 组,则无法更改 Launch 配置组件。即使 ASG 被标记为受污染,terraform 仍然会抛出错误“”

已编辑:添加源代码。 (部分代码示例)

 resource "aws_autoscaling_group" "sample-autoscaling-group" {
  name                 = "sample-asg"
  max_size             = "${var.max_instance_size}"
  min_size             = "${var.min_instance_size}"
  desired_capacity     = "${var.desired_capacity}"
  vpc_zone_identifier  = ["${var.private-subnets}"]
  launch_configuration = "${aws_launch_configuration.sample-launch-configuration.name}"
  health_check_type    = "EC2"

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_launch_configuration" "sample-launch-configuration" {
  name                 = "sample-lc"
  image_id             = "ami-706cca12"
  instance_type        = "t2.small"
  iam_instance_profile = "${aws_iam_instance_profile.ecs-ec2-service-profile.id}"

  lifecycle {
    create_before_destroy = true
  }

  security_groups             = ["${aws_security_group.test_public_sg.id}"]
  associate_public_ip_address = "true"
  key_name                    = "${var.ecs-key-pair-name}"

  user_data = "${file("./templates/user_data.sh")}"
}

如果我更改说 user_data.sh 文件并尝试执行它会失败。

重新阅读 post 和附加配置,我想我错过了实际问题。我将留下下面的解释,因为它可能在某些时候对某人有帮助。至于您的 real 问题,您在启动配置中指定了 create_before_destroy,但它有一个静态名称。启动配置在创建后无法编辑,必须销毁并重新创建 (https://www.terraform.io/docs/providers/aws/r/launch_configuration.html),因此 TF 试图先创建新的,但不能,因为它使用的名称与创建的配置相同已经在那里了。


原始回复(我完全错过了真正的问题):

您似乎正在尝试创建 启动配置 自动缩放组(因为您将两者都定义为 resources)。如果 ASG 已经存在并且不由 terraform 管理,您可能希望使用 data 源引用 ASG(参见文档 here). If you want the ASG to be managed by that terraform config above but it currently isn't, you can look at importing it (see docs here towards the bottom). If the ASG is managed by different terraform, you'll want to look at sharing state between your configs (see docs here)。

上述问题的答案是使用 "name_prefix" 属性,如下所示。这已经解决了这个问题。非常感谢@jstill 不断回来提供可能的选择。

    resource "aws_launch_configuration" "sample-launch-configuration" {
      name_prefix                 = "sample-lc"
      image_id                    = "ami-706cca12"

根据 terraform 文档,给出了以下代码段

Using with AutoScaling Groups Launch Configurations cannot be updated after creation with the Amazon Web Service API. In order to update a Launch Configuration, Terraform will destroy the existing resource and create a replacement. In order to effectively use a Launch Configuration resource with an AutoScaling Group resource, it's recommended to specify create_before_destroy in a lifecycle block. Either omit the Launch Configuration name attribute, or specify a partial name with name_prefix.

可以在 here

查看文档