Govind Kumar
Govind Kumar

Reputation: 139

Encrypt Environment variable and call it in the terraform code

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

For example, I am provisioning a data source 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 = "myDBpwsddnn123"

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 Bitbucket as my repo. I am using AWS Secrets Manager as a centralized repository for all the passwords Then my question is how can I get the environment variable in my Terraform resource, any pointers?

Upvotes: 0

Views: 1253

Answers (2)

chenrui
chenrui

Reputation: 9868

You can read thru this comprehensive guide on dealing with secrets.

Like @severin.julien, personally I find TF_VAR_ is easy to use.

Upvotes: 0

severin.julien
severin.julien

Reputation: 1354

According to the terraform documentation that you can find here: https://www.terraform.io/docs/commands/environment-variables.html

The easiest way to pass an OS environment variable to your terraform you have to do :

First, you need to define your env variable in your terminal like this, you must add the prefix TF_VAR_ to your variable name.

export TF_VAR_database_secret=<my_secret>

And then in your terraform code you could create your terraform variable that has the same name of the OS env variable without the TF_VAR_ prefix.

variable "database_secret" {
    type = string
}

Then you can use the variable like you already did before like for example var.database_secret

Upvotes: 1

Related Questions