Skip to content

Commit

Permalink
feat: init example repo
Browse files Browse the repository at this point in the history
  • Loading branch information
Andy Haynssen authored and Andy Haynssen committed Jan 9, 2020
0 parents commit f8478ee
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
@@ -0,0 +1,4 @@
.idea
.terraform
*.tfstate
*.tfstate.backup
3 changes: 3 additions & 0 deletions README.md
@@ -0,0 +1,3 @@
# Keeping Secrets Out of Terraform State

This repo contains example code for keeping configuration secrets out of the Terraform statefile.
20 changes: 20 additions & 0 deletions main.tf
@@ -0,0 +1,20 @@
provider "aws" {
region = "us-east-1"
}

resource "aws_db_instance" "default" {
name = "postgres_db"
engine = "postgres"
instance_class = "db.t2.micro"
allocated_storage = 20
storage_type = "gp2"
username = "foo"
password = "password123"
db_subnet_group_name = "default-vpc-0ae7dc15b87a40a07"
}

resource "null_resource" "update_password" {
provisioner "local-exec" {
command = "python3 update_password.py --db_identifier=${aws_db_instance.default.identifier}"
}
}
42 changes: 42 additions & 0 deletions update_password.py
@@ -0,0 +1,42 @@
#!/usr/env/bin python3

import argparse
import boto3
import secrets
import string
import time

parser = argparse.ArgumentParser(description='Override Terraform password')
parser.add_argument('--db_identifier', type=str, required=True, help="RDS DB instance identifier")
parser.add_argument('--secret_name', type=str, default='db_password', required=False, help="Name for SSM Parameter")
parser.add_argument('--region', type=str, default='us-east-1', required=False, help="AWS region name")
args = parser.parse_args()


def generate_password(string_length=10):
"""Generate a secure random string of letters, digits and special characters """
password_characters = string.ascii_letters + string.digits + "!#$%^&*()"
return ''.join(secrets.choice(password_characters) for i in range(string_length))


db_id = args.db_identifier
db_password = generate_password(16)
secret_name = args.secret_name
region = args.region

rds = boto3.client('rds', region_name=region)
db = rds.describe_db_instances(DBInstanceIdentifier=db_id)
while rds.describe_db_instances(DBInstanceIdentifier=db_id)["DBInstances"][0]["DBInstanceStatus"] != "available":
time.sleep(3)
response = rds.modify_db_instance(DBInstanceIdentifier=db_id, MasterUserPassword=db_password, ApplyImmediately=True)
if response:
print(f"Updated RDS password for {db_id}")

ssm = boto3.client('ssm')
ssm.put_parameter(
Name=secret_name,
Description=f'DB Password for {db_id}',
Type='SecureString',
Value=db_password,
Overwrite=True
)

0 comments on commit f8478ee

Please sign in to comment.