2

我看过多篇讨论蓝/绿部署的文章,它们始终涉及强制重新启动启动配置和自动缩放组。例如:

https://groups.google.com/forum/#!msg/terraform-tool/7Gdhv1OAc80/iNQ93riiLwAJ

除了将 ASG 的所需容量重置为默认值外,这通常效果很好。因此,如果我的集群负载不足,那么容量会突然下降。

我的问题是:有没有办法在不损失容量的情况下执行 Terraform 蓝/绿部署?

4

2 回答 2

2

我对此没有完整的仅 terraform 解决方案。

我的方法是运行一个小脚本来获取当前所需的容量,设置一个变量,然后在 asg.xml 中使用该变量。

handle-desired-capacity:
    @echo "Handling current desired capacity"
    @echo "---------------------------------"
    @if [ "$(env)" == "" ]; then \
        echo "Cannot continue without an environment"; \
        exit -1; \
    fi
    $(eval DESIRED_CAPACITY := $(shell aws autoscaling describe-auto-scaling-groups --profile $(env) | jq -SMc '.AutoScalingGroups[] | select((.Tags[]|select(.Key=="Name")|.Value) | match("prod-asg-app")).DesiredCapacity'))
    @if [ "$(DESIRED_CAPACITY)" == '' ]; then \
        echo Could not determine desired capacity.; \
        exit -1; \
    fi
    @if [ "$(DESIRED_CAPACITY)" -lt 2 -o "$(DESIRED_CAPACITY)" -gt 10 ]; then \
        echo Can only deploy between 2 and 10 instances.; \
        exit -1; \
    fi
    @echo "Desired Capacity is $(DESIRED_CAPACITY)"
    @sed -i.bak 's!desired_capacity = [0-9]*!desired_capacity = $(DESIRED_CAPACITY)!g' $(env)/terraform.tfvars
    @rm -f $(env)/terraform.tfvars.bak
    @echo ""

显然,这很丑陋,但它确实有效。

我想看看我们是否可以将 ASG 的名称作为远程状态的输出,然后我可以在下一次运行时使用它来获得所需的容量,但我正在努力理解这一点以使其有用。

于 2020-04-30T12:00:11.563 回答
0

作为第二个答案,我将 AWSCLI + jq 包装到 Terraform 模块中。

https://registry.terraform.io/modules/digitickets/cli/aws/latest

module "current_desired_capacity" {
  source            = "digitickets/cli/aws"
  assume_role_arn   = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/OrganizationAccountAccessRole"
  role_session_name = "GettingDesiredCapacityFor${var.environment}"
  aws_cli_commands  = ["autoscaling", "describe-auto-scaling-groups"]
  aws_cli_query     = "AutoScalingGroups[?Tags[?Key==`Name`]|[?Value==`digitickets-${var.environment}-asg-app`]]|[0].DesiredCapacity"
}

module.current_desired_capacity.result为您提供您在 aws_cli_query 中指定的 ASG 当前所需的容量。

同样,这很丑陋,但它的形式化意味着您现在可以从 AWS 访问大量在 Terraform 中尚不可用的属性。

这是一个温和的 hack。没有资源被传递,它纯粹是为单个标量值编写的,所以请小心使用它。

作为作者,我很乐意通过位于https://github.com/digitickets/terraform-aws-cli/issues的 GitHub 问题页面对此进行解释

于 2020-12-26T12:12:26.607 回答