简体   繁体   English

Terraform 用条件设置变量

[英]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.我正在尝试将一个变量设置为一个字符串,该字符串稍后将与另一个字符串连接以用于 aws s3 存储桶策略。 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.我正在使用 terraform 11。

for instance:例如:

  • if set_bucket_policy is false then make the variable an empty string ""如果 set_bucket_policy 为 false 则将变量设为空字符串 ""
  • otherwise use a heredoc to set the string value of the variable否则使用heredoc设置变量的字符串值

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 .有关更多详细信息,您可以查看 Terraform 的条件表达式

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我在我的 ec2 模块中执行此操作以动态设置子网我确实设置了一个变量设置网络 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然后在我的 ec2 代码片段中,我确实检查了子网边界变量并根据它设置了值

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

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

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