HIT_girl
HIT_girl

Reputation: 875

Create multiple aws_cloudformation_stack based on parametrized name with Terraform

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}"
}

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

Upvotes: 1

Views: 544

Answers (1)

Marcin
Marcin

Reputation: 238687

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}"  
}

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

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

Upvotes: 1

Related Questions