Skip to content

Instantly share code, notes, and snippets.

@mmastoras
Last active June 6, 2019 23:25
Show Gist options
  • Save mmastoras/600e4dae073354b85b918d9346d5815c to your computer and use it in GitHub Desktop.
Save mmastoras/600e4dae073354b85b918d9346d5815c to your computer and use it in GitHub Desktop.
Encrypting Secrets w/ KMS for use in terraform
# Encrypt a key for use in aws secrets manager terraform state files
1. Encrypt a secret using the aws cli
$ echo "<secret>" | tr -d '\n' > secret.txt # strip the newline from the echo
$ aws kms encrypt --key-id alias/aws/secretsmanager --plaintext fileb://secret.txt --encryption-context "type=password,env=staging" --output text --query CiphertextBlob | pbcopy
2. Create the aws_kms_secrets data resource in terraform
data "aws_kms_secrets" "mercury" {
secret {
name = "staging_db_password"
payload = "<insert value returned in above kms encrypt call>"
context {
type = "password"
env = "staging"
}
}
}
3. Create the aws secrets manager terraform resources
resource "aws_secretsmanager_secret" "mercury_staging_db_password" {
kms_key_id = "aws/secretsmanager"
name = "/concourse/track/mercury_staging_db_password"
description = "Credentials for staging mercury database"
}
resource "aws_secretsmanager_secret_version" "mercury_staging_db_password" {
secret_id = "${aws_secretsmanager_secret.mercury_staging_db_password.id}"
secret_string = "${data.aws_kms_secrets.mercury.plaintext["staging_db_password"]}"
}
# Decrypt secret
$ aws kms decrypt --ciphertext-blob fileb://encrypted_file --output text --encryption-context "type=password,env=staging" --query Plaintext | base64 --decode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment