Reputation: 2625
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!
Upvotes: 2
Views: 3729
Reputation: 56877
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.
Upvotes: 7
Reputation: 2625
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"
Upvotes: 0