简体   繁体   中英

Terraform using count for both looping a variable and if statement to create the resource

I have a resource that I only need to create depending on the value of a variable (if environment == "prod"), The same resource is creating multiple folders on s3 also. takes another variable (list) and iterates through it to create the folder.

So these are the resources:

variable "s3_folders" {
  type        = list
  description = "The list of S3 folders to create"
  default     = ["ron", "al", "ted"]
}

resource "aws_s3_object" "smcupdater-folder-new-out" {
    count  = "${length(var.s3_folders)}"
    count      = var.environment == "prod" ? 1 : 0
    bucket = var.bucketname-smc-updater-upgrades
    acl    = "private"
    key    = "UpdaterActions/${var.s3_folders[count.index]}/NewActionsFiles/out-smcupdater/"
    source = "/dev/null"
    server_side_encryption = "AES256"
}

But I obviously can not use the count twice, I also tried with for each but this is also not allowed, Is there another way to do it that I'm missing?

Yes, you can just update the ternary expression to do this:

resource "aws_s3_object" "smcupdater-folder-new-out" {
    count  = var.environment == "prod" ? length(var.s3_folders) : 0
    bucket = var.bucketname-smc-updater-upgrades
    acl    = "private"
    key    = "UpdaterActions/${var.s3_folders[count.index]}/NewActionsFiles/out-smcupdater/"
    source = "/dev/null"
    server_side_encryption = "AES256"
}

This way you are checking if the environment is prod and if so you are setting the count meta-argument to the length of the variable s3_folders .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM