This is going to be a short article, showing a couple of ways to output terraform sensitive data.
If you don’t know what that is, basically, you can declare a variable as sensitive and terraform will prevent that data from appearing in CLI and log output. But beware – the data is still saved in the terraform statefile in plaintext, so make sure you secure and limit access to your terraform statefiles.
Method 1: Terraform output raw
If you have an output value that is based on a sensitive variable or attribute, you will get an error message unless you add the declaration: sensitive = true
. This error forces you to be explicit about declaring an output that is based on a sensitive variable or attribute.
output "db_password" {
value = aws_db_instance.default.password
sensitive = true # this is required to output sensitive values
}
However, even after adding sensitive = true
to the output, the value will still be masked with <sensitive>
.
There is a way, however, to output the value in plaintext. Let’s walk through an example.
Declare a variable as sensitive and try to print it as an output:
variable "mysecretvar" {
type = string
sensitive = true
}
output "mysecretvar" {
value = var.mysecretvar
}
Running apply or plan on this code will result in an error (terraform v1.5.5 at time of this writing):
❯ terraform apply -no-color
Error: Output refers to sensitive values
on main.tf line 8:
8: output "mysecretvar" {
To reduce the risk of accidentally exporting sensitive data that was intended to be only internal, Terraform requires that any root module output containing sensitive data be explicitly marked as sensitive, to confirm your intent.
If you do intend to export this data, annotate the output value as sensitive by adding the following argument:
sensitive = true
Let’s fix the error by adding sensitive = true
to the output:
variable "mysecretvar" {
type = string
sensitive = true
}
output "mysecretvar" {
value = var.mysecretvar
sensitive = true
}
The error is gone, but the value is still not displayed in plaintext:
❯ terraform output
mysecretvar = <sensitive>
So how do you display the output in plaintext? Use terraform output with the -raw
flag:
❯ terraform output -raw mysecretvar
secret-data
Method 2: The nonsensitive() function
The nonsensitive() function, as the name implies, will prevent masking and expose your sensitive data. It is a convenient way to output sensitive data in plaintext. I usually only use this while debugging. Please make sure you are aware of the security implications of outputting your sensitive value as plaintext.
This is very straightforward to use – you simply supply the output value to the function and remove the sensitive declaration:
variable "mysecretvar" {
type = string
sensitive = true
}
output "mysecretvar" {
value = nonsensitive(var.mysecretvar)
}
Our output is now treated like any other non-sensitive output:
❯ terraform output
mysecretvar = "secret-data"
That’s it – I did promise this would be a short one 😀