Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Interpolation in Terraform

Tags:

terraform

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")}"
like image 587
MMA Avatar asked Mar 24 '17 04:03

MMA


People also ask

Does Terraform allow variable interpolation?

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.

What is interpolation Terraform?

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.

Can I use variables in Tfvars?

tfvars values only apply to variables in the root module. The root .

What does EOT mean in Terraform?

EOT in this case stands for "end of text".


2 Answers

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.

like image 55
Martin Atkins Avatar answered Oct 11 '22 22:10

Martin Atkins


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'
like image 45
Innocent Anigbo Avatar answered Oct 11 '22 22:10

Innocent Anigbo