MySQLClientUsingAWSSecretsManager

nicolaw 17th January 2022 at 1:55pm
AWS AWS IAM awscli CodeSnippets
  • Create your secret in AWS Secrets Manager.
  • Attach a suitible IAM policy your EC2 instance profile:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetResourcePolicy",
                "secretsmanager:GetSecretValue",
                "secretsmanager:DescribeSecret",
                "secretsmanager:ListSecretVersionIds"
            ],
            "Resource": "arn:aws:secretsmanager:eu-west-2:123456789012:secret:trinitycore-*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "secretsmanager:GetRandomPassword",
            "Resource": "*"
        }
    ]
}
  • Use the mysql --defaults-file or --defaults-extra-file argument to inject the credentials using the aws CLI tool:
# mysql --defaults-extra-file=<(aws --region "$(cloud-init query region)" secretsmanager get-secret-value --secret-id trinitycore-database-master --output text --query 'SecretString' | jq -r '["[client]", "user="+.username, "password="+.password, "port="+(.port|tostring), "host="+.host]|join("\n")')
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 4751
Server version: 8.0.23 Source distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> Bye

Example output generated by the AWS CLI in conjunction with jq:

# aws --region "$(cloud-init query region)" secretsmanager get-secret-value --secret-id trinitycore-database-master --output text --query 'SecretString' | jq -r '["[client]", "user="+.username, "password="+.password, "port="+(.port|tostring), "host="+.host]|join("\n")'
[client]
user=admin
password=**RedactedSecurePasswordHere**
port=3306
host=trinitycore-database.ff745aac1239.eu-west-2.rds.amazonaws.com