Reputation: 2348
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:
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
}
Upvotes: 0
Views: 16464
Reputation: 3606
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" = ""
}
Upvotes: 0
Reputation: 745
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
Upvotes: 1