是否可以基于参数化名称,在地形中使用一个aws_cloudformation_stack
资源定义创建多个CloutFormation堆栈?我定义了以下资源,我希望每个app_name
、app_env
和build_name
组合都有一个堆栈:
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
时,旧堆栈将被删除,并创建一个新堆栈,但我希望保留旧堆栈并创建新堆栈
一种方法是将变量build_name
定义为列表。然后,当您创建新的构建时,只需将它们附加到列表中,并在for_each的帮助下创建堆栈来迭代构建名称。
例如,如果您有以下内容:
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"
:
variable "build_name" {
default = ["test3", "new_build"]
}