Published on

Using Terraform to Store Passwords in AWS SecretsManager

Authors

In this post we will use the terraform random_password resource to generate a password, then we will provide it as an input to the aws_secretsmanager_secret_version to store our password in aws secretsmanager.

Terraform

In our main.tf we define our resources:

main.tf
resource "random_password" "db_password" {
  length           = 40
  special          = true
  min_special      = 5
  override_special = "!#$%^&*()-_=+[]{}<>:?"
}

resource "aws_secretsmanager_secret" "db_secrets" {
  name = "/dev/myapp/db-secrets"
}

resource "aws_secretsmanager_secret_version" "db_secrets_version" {
  secret_id = aws_secretsmanager_secret.db_secrets.id

  secret_string = jsonencode(
    {
      username = "db_admin"
      password = random_password.db_password.result
      engine   = "postgresql"
      host     = "postgres-example.rds.amazonaws.com"
    }
  )
}

We also need to provide our provider.tf so that we can use the aws provider and also authenticate:

provider.tf
terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "4.23.0"
    }
  }
}

provider "aws" {
  region                   = "eu-west-1"
  profile                  = "default"
  shared_credentials_files = ["~/.aws/credentials"]
}

Once we have set that we can initialize terraform by downloading the providers:

terraform init

Then run a plan to preview what will be deployed:

terraform plan

Once you are happy, you can deploy the infrastructure using:

terraform apply

Your secret in aws secretsmanager should now have the following content:

{
  "username":  "db_admin"
  "password":  "<password-from-provider>"
  "engine":    "postgresql"
  "host":      "<the-postgres-endpoint>"
}

Thank You

Thanks for reading, if you like my content, feel free to check out my website, and subscribe to my newsletter or follow me at @ruanbekker on Twitter.

Join my Newsletter?
Buy Me A Coffee