使用 Terraform 根据参数化名称创建多个 aws_cloudformation_stack [英] Create multiple aws_cloudformation_stack based on parametrized name with Terraform

查看:24
本文介绍了使用 Terraform 根据参数化名称创建多个 aws_cloudformation_stack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据参数化名称在 terraform 中使用一个 aws_cloudformation_stack 资源定义创建多个 CloutFormation 堆栈?我定义了以下资源,我希望每个 app_nameapp_env build_name 组合都有一个堆栈:

Is it possible to create multiple CloutFormation stacks with one aws_cloudformation_stack resource definition in terraform, based on parametrized name ? I have the following resources defined and I would like to have a stack per app_name, app_env build_name combo:

resource "aws_s3_bucket_object" "sam_deploy_object" {
  bucket = var.sam_bucket
  key    = "${var.app_env}/${var.build_name}/sam_template_${timestamp()}.yaml"
  source = "../.aws-sam/sam_template_output.yaml"
  etag   = filemd5("../.aws-sam/sam_template_output.yaml")
}
resource "aws_cloudformation_stack" "subscriptions_sam_stack" {
  name         = "${var.app_name}---${var.app_env}--${var.build_name}"
  capabilities = ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]
  template_url = "https://${var.sam_bucket}.s3-${data.aws_region.current.name}.amazonaws.com/${aws_s3_bucket_object.sam_deploy_object.id}"
}

当我在 build_name 名称更改时运行 terraform apply 时,旧堆栈被删除并创建一个新堆栈,但是我想保留旧堆栈并创建一个新的

When I run terraform apply when build_name name changes, the old stack gets deleted and a new one created, however I would like to keep the old stack and create a new one

推荐答案

一种方法是将你的变量 build_name 定义为一个列表.然后,当您创建新构建时,您只需将它们附加到列表中,并在 for_each 迭代构建名称.

One way would be to define your variable build_name as a list. Then, when you create new build, you just append them to the list, and create stacks with the help of for_each to iterate over the build names.

例如,如果您有以下情况:

For example, if you have the following:

variable "app_name" {
  default = "test1"
}

variable "app_env" {
  default = "test2"
}


variable "build_name" {
  default = ["test3"]
}

resource "aws_cloudformation_stack" "subscriptions_sam_stack" {

  for_each     = toset(var.build_name) 
  
  name         = "${var.app_name}---${var.app_env}--${each.value}"
  capabilities = ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]
  template_url = "https://${var.sam_bucket}.s3-${data.aws_region.current.name}.amazonaws.com/${aws_s3_bucket_object.sam_deploy_object.id}"  
}

然后,如果您想为堆栈进行第二次构建,您只需扩展 variable build_name":

Then if you want second build for the stack, you just extend variable "build_name":

variable "build_name" {
  default = ["test3", "new_build"]
}

这篇关于使用 Terraform 根据参数化名称创建多个 aws_cloudformation_stack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆