declare a variable using `execute` Interpolation in Terraform

江枫思渺然 提交于 2020-01-15 07:04:12

问题


I want to declare a a sub-string of a variable to another variable. I tested taking a sub-string using terraform console.

> echo 'element(split (".", "10.250.3.0/24"), 2)' | terraform console
> 3

my subnet is 10.250.3.0/24 and I want my virtual machine to get private IP address within this subnet mask 10.250.3.6. I want this to get automatically assign by looking at subnet address. What I've tried;

test.tf

variable subnet {
  type = "string"
  default = "10.250.3.0/24"
  description = "subnet mask myTestVM will live"
}

variable myTestVM_subnet {
  type = "string"
  default = "10.250." ${element(split(".", var.trusted_zone_onpremises_subnet), 2)} ".6"
}

And then I test it by

terraform console
>Failed to load root config module: Error parsing /home/anum/test/test.tf: At 9:25: illegal char

I guess its just simple syntax issue. but couldn't figure out what!


回答1:


As you've seen, you can't interpolate the values of variables in Terraform.

You can, however, interpolate locals instead and use those if you want to avoid repeating yourself anywhere.

So you could do something like this:

variable "subnet" {
  type = "string"
  default = "10.250.3.0/24"
  description = "subnet mask myTestVM will live"
}

locals {
  myTestVM_subnet = "10.250.${element(split(".", var.trusted_zone_onpremises_subnet), 2)}.6"
}

resource "aws_instance" "instance" {
  ...
  private_ip = "${local.myTestVM_subnet}"
}

Where the aws_instance is just for demonstration and could be any resource that requires/takes an IP address.

As a better option in this specific use case though you could use the cidrhost function to generate the host address in a given subnet.

So in your case you would instead have something like this:

resource "aws_instance" "instance" {
  ...
  private_ip = "${cidrhost(var.subnet, 6)}"
}

Which would create an AWS instance with a private IP address of 10.250.3.6. This can then make it much easier to create a whole series of machines that increment the IP address used by using the count meta parameter.




回答2:


Terraform doesn't allows interpolations declaration of variables in default. So I get ;

Error: variable "myTestVM_subnet": default may not contain interpolations

and the syntax error really got fixed after banging my head, so here is what Terraform likes;

private_ip_address = "10.250.${element(split(".", "${var.subnet}"), 2)}.5"


来源:https://stackoverflow.com/questions/49737497/declare-a-variable-using-execute-interpolation-in-terraform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!