terraform,

Decrypt iam_user_login_profile password in Terraform

Dec 29, 2021 · 2 mins read · Post a comment

It’s almost always not a good idea to decrypt aws_iam_user_login_profile password to Terraform output since there are better approaches, which will not be covered in this topic today. But just for the sake of argument, roll up your sleeves and try to decrypt it from the command line, by following the steps below.

Prerequisites

  • Terraform
  • GPG

Solution

Step 1. Let’s take the following TF block as an example:

data "local_file" "pgp_key_devcoops" {
  filename = "./public-key-devcoops.gpg"
}

resource "aws_iam_user" "devcoops" {
  name          = "devcoops"
  path          = "/"
}

resource "aws_iam_user_login_profile" "devcoops" {
  user    = aws_iam_user.devcoops.name
  pgp_key = data.local_file.devcoops.content_base64
}

output "password" {
  value = aws_iam_user_login_profile.devcoops.encrypted_password
}

Step 2. init, plan and apply the TF changes.

terraform init
terraform plan
terraform apply --auto-aprove

Step 3. Now, terraform output the encrypted password.

terraform output password

Output:

password = "mdACA5K/6v...etToy93/1GCANN=="

Step 4. The encrypted password is wrapped in double quotes. Get rid of them by saving the pass value to a temp file and manually remove the quotes, or use local variables. For instance:

enc_pass_with_quotes=$(terraform output password)
enc_pass_wo_quotes=${enc_pass_with_quotes:1:-1}

Step 5. Set the environment variable GPG_TTY as per below:

export GPG_TTY=$(tty)

Step 6. Finally, decrypt the password and the value will be printed to the standard output.

echo $enc_pass_wo_quotes | base64 --decode | gpg --decrypt

Or, if you have saved the password in a temp plain text file instead, run the following command:

cat temp_file_enc_pass_wo_quotes | base64 --decode | gpg --decrypt

Output:

devcoops321_change_this_pass

Note(s):

  • You might be prompt for the GPG signing key password though.
  • Even though, the official TF documentation suggests using keybase gpg decrypt instead of gpg --decrypt, i was getting keybase command not found errors all the time. So, my advice is to try with both, whatever works for you.

Conclusion

Overall, as stated before, this is not a good practice at all. Use secrets management solution instead. Terraform is HashiCorp’s IaC product which integrates really well with HashiCorp’s Vault, or any other public cloud provider secret management service, including Azure Key Vault and AWS Secrets Manager.
Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.