How to handle secret variables in Terraform? Environment variable?

Hi All,

How can I make the values of variables as secrets or access them as environment variables in Terraform?

For example, I am provisioning a datasource resource, e.g.

resource "aws_rds_cluster" "aurora" {

    cluster_identifier            = var.db_cluster_identifier
    database_name                 = var.rds_db_name
    master_username               = var.rds_master_username
    master_password               = var.rds_master_password
    backup_retention_period       = var.backup_retention_period
    preferred_backup_window       = var.preferred_backup_window
    preferred_maintenance_window  = var.preferred_maintenance_window
    db_subnet_group_name          = aws_db_subnet_group.aurora.name
    #final_snapshot_identifier     = var.db_snapshot_cluster_identifier
    vpc_security_group_ids        = [aws_security_group.allow-aurora-db.id]
    skip_final_snapshot           = true
    ...

In here, i have a parameter like:
master_password = var.rds_master_password

whose value I am getting as plain text stored in my “terraform.tfvars”, e.g.
rds_master_password = "myDBPassword123"

My question is if I store the encoded value in the “terraform.tfvars”, is there any way i can decode it in my resource file?

I am using Gitlab as my repo. I can also store the value as an environment variable in Gitlab. Then my question is how can I get the environment variable in my Terraform resource, any pointers?

Thanks

Environment variables are used in the form TF_VAR_name (https://www.terraform.io/docs/commands/environment-variables.html#tf_var_name). This means that if you need a varibale FOO in your code, you have to export TF_VAR_foo.

Alternatively, you can use Vault (https://www.terraform.io/docs/providers/vault/index.html).

I use environment variables.

Thanks it worked.

Gitlab variable: BASE64_RDS_MASTER_PASSWORD_PROD
Terraform variable: rds_master_password

RDS_MASTER_PASSWORD: “$BASE64_RDS_MASTER_PASSWORD_PROD”

  • export TF_VAR_rds_master_password=$(echo “$RDS_MASTER_PASSWORD” | base64 -d)

ps:
stored in the project Git variable with encoded base64 value.

To keep secrets from being readable in Git, I use git-crypt

thanks, will look into that as well.