Secure Database password using EC2 parameter store

Please visit my website and subscribe to my youtube channel for more articles


  1. IAM Policy
  2. IAM Role
  3. Encryption Keys
  4. Parameter Store
  5. EC2 Instance — Assume IAM role
  6. Install PHP SDK on AWS
  7. Configured php code to retrieve db credentials

1. IAM policy

Open the AWS Console and navigate to IAM -> Policies and click Create policy. Next, select Create Your Own Policy, and use the following Policy Document:

APPLICATION_SECRET_API_KEY - this is the key which we will create later{
“Version”: “2012–10–17",
“Statement”: [
“Effect”: “Allow”,
“Action”: [
“Resource”: “*”
“Effect”: “Allow”,
“Action”: [
“Resource”: [

2. IAM Role

Go to IAM -> Roles and click Create new role, then choose Amazon EC2 for the AWS Service Role.

Attach the policy which you have created above

Role is created with the permissions.

3. Create Keys

Go to IAM ->Encryption Keys -> Select Region where you want to create key

Click on Create Key

Next, enter an Alias for your key and an optional Description. For Key Material Origin, leave the default KMS selected.

You can add Tags if you need.

Key administrators

The key administrator is an IAM User or Role who is allowed to make changes to the key itself or grant others access to use and administer it.

Next, we’ll Define Key Usage Permissions so that we can actually use our key. Here, I’ve selected the IAM Role as an authorized key user, which is the role I’ll be assigning to the EC2 instances my application is going to run on.

Key is created successfully.

Encrypting our secret

Go to EC2 -> Parameter Store

Retrieve Plaintext value

Key setup is done successfully.

How to use it with Application Code

You need to install php sdk. Click here for installation details

Download as a zip

and unzip the folder and place it in your application folder

Below is the sample code for php

require ‘/var/www/html/openemr/test/aws-autoloader.php’;
use Aws\Ssm\SsmClient;
$client = new SsmClient([
‘version’ => ‘latest’,
‘region’ => ‘us-west-2’,
$result = $client->getParameters([
‘WithDecryption’ => true

$host = ‘hostname’;
$port = ‘3306’;
$login = ‘openemr’;
$pass = $result[‘Parameters’][0][‘Value’];
$dbase = ‘emrdb’;

EC2 Instance

Instance has to assume the role which you have created above.

Written by

Devops Automation Enginneer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store