I am having trouble in variable interpolation in terraform. Here is what my terraform configuration looks like. i.e variable inside builtin function
variable "key" {}
ssh_keys {
path = "/home/${var.provider["user"]}/.ssh/authorized_keys"
key_data = "${file(${var.key})}"
}
Command: terraform apply -var 'key=~/.ssh/id_rsa.pub'
It's not reading the value of "key" from command line argument or from env variable. However when i hardcore the value in .tf file, it works. Like below.
key_data = "${file("~/.ssh/id_rsa.pub")}"
Embedded within strings in Terraform, whether you're using the Terraform syntax or JSON syntax, you can interpolate other values. These interpolations are wrapped in ${} , such as ${var. foo} . The interpolation syntax is powerful and allows you to reference variables, attributes of resources, call functions, etc.
So, mathematically speaking, interpolation is a method of constructing new data points within the range of a discrete set of known data points. Now, Terraform has been using this terminology to reference values, like variables.
tfvars values only apply to variables in the root module. The root .
EOT in this case stands for "end of text".
The ${ ... }
syntax is only used when embedding an expression into a quoted string. In this case, where your var.key
variable is just being passed as an argument to a function already within a ${ ... }
sequence, you can just reference the variable name directly like this:
key_data = "${file(var.key)}"
Nested ${ ... }
sequences are sometimes used to pass an interpolated string to a function. In that case there would first be a nested set of quotes to return to string context. For example:
key_data = "${file("${path.module}/${var.key_filename}")}"
In this more complicated case, the innermost string expression is first evaluated to join together the two variables with a /
, then that whole string is passed to the file
function, with the result finally returned as the value of key_data
.
It doesn't work because you were using the wrong flag for the scenario you described above.
If you want to specify a path to a file use the "-var-file" flag as follow:
terraform apply -var-file=~/.ssh/id_rsa.pub
If you must use the "-var" flag then you must specify the content of the file as follow:
terraform apply -var 'key=contenctOFPublicKey'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With