Terraform – Output sensitive variables as plaintext (how to use the nonsensitive() terraform function)

Terraform reference: terraform sensitive data.
Using terraform v1.9.3 into the below tests

Are you trying to export a variable in Terraform and aren’t being able to do so?

Do you receive a message stating that that variable is sensitive and you can only output it with `sensitive=true`?

Well, here are the ways you can work with sensitive data in Terraform in order to output it in clear text or as sensitive value.

And remember: Data is always saved in the terraform statefile as plaintext. For that reason, make sure you keep safe and limit access to your terraform statefiles!

Method 1: terraform output -raw

The first method is to add the sensitive = true to the output value in order to be able to print the output as “<sensitive>”. Still not the plaintext value.

In the example below we are using a local var with sensitive value, but you could also do it when using a data from a module output that is also flagged as sensitive:

variable "secret_variable" {
  type      = string
  sensitive = true
}

output "secret_variable" {
    value = var.secret_variable
}

Running terraform apply or plan on this code will result in an error:

$ terraform apply

Error: Output refers to sensitive values

  on main.tf line 7:
   8: output "secret_variable" {

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

Following the recommendation to fix the error:

variable "secret_variable" {
  type      = string
  sensitive = true
}

output "secret_variable" {
  value     = var.secret_variable
  sensitive = true
}

As you can see, now error is gone and value is printed as <sensitive>, not yet in plaintext:

❯ terraform output
secret_variable = <sensitive>

To print the value in plaintext, use terraform output with the -raw flag or the method 2 below:

❯ terraform output -raw secret_variable
MySuperDevOps.clickSecret!

Method 2: Using nonsensitive() function

Using the nonsensitive() function will prevent masking and expose your sensitive data.
It is convenient, but also dangerous and may be used only while debugging your code.

To output value directly in plaintext, use the nonsensitive() function and remove the sensitive=true declaration:

variable "secret_variable" {
  type      = string
  sensitive = true
}


output "secret_variable" {
  value     = nonsensitive(var.secret_variable)
}

Now you can see the value in plaintext directly in terraform output:

❯ terraform output
secret_variable = "MySuperDevOps.clickSecret!"

That’s all folks 😉

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *