简体   繁体   English

Terraform 使用 count 循环变量和 if 语句来创建资源

[英]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.我有一个资源,我只需要根据变量的值创建(如果环境 ==“prod”),同样的资源也在 s3 上创建多个文件夹。 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 .通过这种方式,您可以检查环境是否为生产环境,如果是,则将count元参数设置为变量prods3_folders

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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