Variable interpolation in Terraform
I am having problems with variable interpolation in terraform. This is what my terraform config looks like. ie variable inside inline 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 does not read the value "key" from the command line argument or from the env variable. However, when I hardcore the value in the .tf file, it works. As below.
key_data = "${file("~/.ssh/id_rsa.pub")}"
source to share
The syntax ${ ... }
is only used when embedding an expression in a quoted string. In this case, when your variable is var.key
simply passed as an argument to a function already in the sequence ${ ... }
, you can simply refer to the variable name like this:
key_data = "${file(var.key)}"
Nested ${ ... }
sequences are sometimes used to pass an interpolated string to a function. In this case, there must be a nested set of quotes first to return to the string context. For example:
key_data = "${file("${path.module}/${var.key_filename}")}"
In this more complex case, the innermost string expression is first evaluated to concatenate the two variables with /
, then the entire entire string is passed to the function file
, after which the result is returned as a value key_data
.
source to share
It doesn't work because you used the wrong flag for the above scenario.
If you want to specify the path to a file, use the "-var-file" flag:
terraform apply -var-file=~/.ssh/id_rsa.pub
If you must use the "-var" flag, you must specify the contents of the file as follows:
terraform apply -var 'key=contenctOFPublicKey'
source to share