How to provide the Terraform Cloud API token using an environment variable?
In my CI environment (Bitbucket pipelines) I'm trying to use the new Terraform Cloud remote state management. The announcement video clearly states you can use environment variables instead of the .terraformrc
file to pass your API token. However, I cannot find any documentation on the exact environment variable I have to use.
I followed the getting started guide about Terraform Cloud, but there they also don't mention anything about environment variables.
I also looked at the environment variables section of the Terraform documentation, but there was also no mentioning of how to set (or override) the cli configuration.
If you are using the Terraform Cloud/Enterprise provider, you could set the TFE_TOKEN
environment variable.
Alternatively, you could write the terraform config file temporarily during the build, e.g.:
# Set environment variable
MY_TF_TOKEN='abc.123.abc123'
# Create .terraformrc with credential config for user
cat >~/.terraformrc <<EOL
credentials "app.terraform.io" {
token = "${TF_CLOUD_TOKEN}"
}
EOL
Otherwise, you could (but not recommended) manipulate the credentials.tfrc.json
in ~/.terraform.d
but beware that this may be overwritten when running terraform commands. For example using jq in bash:
# Set environment variable
MY_TF_TOKEN='abc.123.abc123'
# Create json from environment variable and (over)write expected file
jq --arg token $MY_TF_TOKEN \
'{"credentials":{"app.terraform.io":{"token": $token}}}' \
> ~/.terraform.d/credentials.tfrc.json
You should get the following when e.g. running cat ~/.terraform.d/credentials.tfrc.json
:
{
"credentials": {
"app.terraform.io": {
"token": "abc.123.abc123"
}
}
}