简体   繁体   中英

Terraform set variable with condition

I'm trying to set a variable to a string that will later be joined with another string for an aws s3 bucket policy. I'm trying to do this by defining a local variable, but I also need to specify a condition in which I would want to use this. I am using terraform 11.

for instance:

  • if set_bucket_policy is false then make the variable an empty string ""
  • otherwise use a heredoc to set the string value of the variable

example, not working code:

locals {
  my_bucket_policy = var.set_bucket_policy == "false" ? "" : <<EOF
  {
    "Action": "s3:Get*",
    "Effect": "Allow",
    "Principal": {
      "AWS": "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/myrole"
    },
    "Resource": [
      "arn:aws:s3:::mybucket",
      "arn:aws:s3:::mybucket/*"
    ],
    "Sid": ""
  }
  EOF
}

I think this is pretty close, I created a small sample showing how to use conditionals. For more details, you can check out Terraform's Conditional Expressions .

main.tf

variable "set_bucket_policy" {
    type = bool
}

output "my_bucket_policy" {
    value = var.set_bucket_policy == false ? "is set to false" : "is set to true"
}

Sample Output

% terraform apply -var 'set_bucket_policy=false' -auto-approve

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

my_bucket_policy = is set to false
% terraform apply -var 'set_bucket_policy=true' -auto-approve

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

my_bucket_policy = is set to true

there are ways to do it and everyone do it in there own way i did it in this way.

i will check directly bucket policy variable like

bucket_policy_variable = var.bucket_policy == false : "" ? var.bucketpolicy_json 

I did this in my ec2 module to set subnet dynamically i did set one variable setting up network scope

  variable "subnet_boundary" {
  description = "Variable to declare instance network boundary it could be public or private"
  default = "public"
}

Then in my ec2 code snippet i did check subnet_boundary variable and set the the value based on it

  subnet_id              = var.subnet_boundary == "public" ? var.ec2_public_subnets : var.ec2_private_subnets 

And it works like charm

  + source_dest_check                    = true
  + subnet_id                            = "sn-pubxxxxxx"
  + tags                                 = {
      + "Name" = ""
    }

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