How to get parameter values from AWS Systems Manager Parameter Store using AWS SDK for Python (Boto3)

How to get parameter values from AWS Systems Manager Parameter Store using AWS SDK for Python (Boto3)

Clock Icon2018.08.12

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

AWS Systems Manager Parameter Store is a service which manages sensitive data. By using Parameter Store, you can separate your sensitive data from your code. This time, we will illustrate how to get parameter values from Parameter Store.

Put data to Parameter Store

In the beginning, we will add data to Parameter Store to use sample code. Since I think that you use Management Console or AWS CLI when adding data in Parameter Store, we will add data using AWS CLI. In the following example, it is encrypted with AWS KMS as --type "SecureString" option.

$ aws ssm put-parameter --name "RDS-MASTER-PASSWORD" --value 'PASSWORD' --type "SecureString"

Sample Code

get_parameters() is a simple function to get parameter values from Parameter Store. It returns the value for the parameter name stored in the parameter decrypted with WithDecryption=True.

Executing this sample code will get the decrypted string PASSWORD.

import boto3

# SSM region
REGION = 'us-west-2'


# Function for get_parameters
def get_parameters(param_key):
    ssm = boto3.client('ssm', region_name=REGION)
    response = ssm.get_parameters(
        Names=[
            param_key,
        ],
        WithDecryption=True
    )
    return response['Parameters'][0]['Value']


def main():

    # parameter name
    param_key = "RDS-MASTER-PASSWORD"

    # get parameter value
    param_value = get_parameters(param_key)
    print(param_value)


if __name__ == '__main__':
    main()

Execution result

$ python get-parameters.py
PASSWORD

Conclusion

We introduced get_parameters() because it is a general purpose function. By using the AWS Systems Manager Parameter Store, you do not have to write passwords or credential data in your code. It is easy to use so please try using it.

References

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.