首页 > 解决方案 > 如何防止 Terraform 用 CodeDeploy 替换 ECS 服务

问题描述

原来的

我正在使用 AWS CodeDeploy 更新 ECS 服务。在 CodeDeploy 部署期间,它将更改目标组在 Terraform 中的配置方式。这会产生一个问题,因为 Terraform 将覆盖当前的负载均衡器并导致服务暂时不可用。

如何告诉 Terraform 避免更改目标组?我尝试过使用lifecycle块,但 Terraform 无法应用,因为看起来根本没有负载均衡器。

也许更好的问题是,如何在同一个应用程序中管理 Terraform 更新和 CodeDeploy?

下面是在 CodeDeploy 之后对 Terraform 的更改。

  - load_balancer { # forces replacement
      - container_name   = "service" -> null
      - container_port   = 3000 -> null
      - target_group_arn = "{...}service-green{...}" -> null
    }
  + load_balancer { # forces replacement
      + container_name   = "service"
      + container_port   = 3000
      + target_group_arn = "{...}service{...}"
    }

例子

resource "aws_ecs_service" "default" {
  name                               = "service"
  cluster                            = "cluster"
  launch_type                        = "FARGATE"
  task_definition                    = definition.default.arn
  desired_count                      = 1

  deployment_controller {
    type = var.deployment_controller_type
  }

  network_configuration {
    security_groups = aws_security_group.service[*].id
    subnets         = data.aws_subnet_ids.private.ids
  }

  dynamic "load_balancer" {
    for_each = local.load_balancers.public.enabled ? [1] : []
    content {
      target_group_arn = aws_alb_target_group.public[load_balancer.key].arn
      container_name   = local.service_name
      container_port   = var.container_port
    }
  }

  lifecycle {
    ignore_changes = [
      desired_count,
      task_definition
    ]
  }
}

尝试的解决方案:

  lifecycle {
    ignore_changes = [
      desired_count,
      task_definition,
      load_balancer
    ]
     prevent_destroy = true
  }

标签: amazon-web-servicesterraformamazon-ecs

解决方案


我通过使用

resource "aws_lb_listener" "lb_https_listeners"
  ...
  lifecycle {
    ignore_changes = [default_action[0].target_group_arn]
  }

但是,如果您尝试使用 splat,您会得到

A single static variable reference is required: only attribute access and
indexing with constant keys. No calculations, function calls, template
expressions, etc are allowed here.

您也许可以使用动态块来忽略更改?我没有尝试,因为即使我目前有一个动态块,我也只会在可预见的未来使用一个。


推荐阅读