Search code examples
python-3.xssm

Lambda Python to Query SSM Parameter Store - get value is failing


I couldn't get the value of my parameter.

I'm working with a lambda in Python.

ssm =boto3.client('ssm')

def eslam(event, context):


    parameters = ssm.get_parameters(
        Names=[
            '/dev/es/ad-es-to-s3',
        ],
        WithDecryption=False
    )

    x = parameters.values()
    print(x)
    '''
    This print: dict_values([[{'Name': '/dev/es/ad-es-to-s3', 'Type': 'String', **'Value': "'k1':'valor1', 'k2':'valor2', 'k3':'valor3'"**, 'Version': 1, 'LastModifiedDate': datetime.datetime(2019, 10, 16, 16, 50, 38, 155000, tzinfo=tzlocal()), 'ARN': 'arn:aws:ssm:us-east-1:xxxxxxxxxx:parameter/dev/es/ad-es-to-s3'}], [], {'RequestId': 'xxxxxxxx1', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'xxxxxxxxxx', 'content-type': 'application/x-amz-json-1.1', 'content-length': '260', 'date': 'Wed, 16 Oct 2019 17:01:38 GMT'}, 'RetryAttempts': 0}])
    '''

    print(parameters)
    '''
    this print: {'Parameters': [{'Name': '/dev/es/ad-es-to-s3', 'Type': 'String', **'Value': "'k1':'valor1', 'k2':'valor2', 'k3':'valor3'"**, 'Version': 1, 'LastModifiedDate': datetime.datetime(2019, 10, 16, 16, 50, 38, 155000, tzinfo=tzlocal()), 'ARN': 'arn:aws:ssm:us-east-1:xxxxxxxxxxx:parameter/dev/es/ad-es-to-s3'}], 'InvalidParameters': [], 'ResponseMetadata': {'RequestId': 'xxxxxxxxxx', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'xxxxxxxxx', 'content-type': 'application/x-amz-json-1.1', 'content-length': '260', 'date': 'Wed, 16 Oct 2019 17:01:38 GMT'}, 'RetryAttempts': 0}}
    '''
   print(parameters['Parameter']['Value'])
   # this raise the error: "errorType": "KeyError"

   return parameters.get('Parameter', {}).get('Name')
   # this return a null value, **I want to get 'Value': "'k1':'valor1', 'k2':'valor2', 'k3':'valor3'"**

Solution

  • You are using the get_parameters (plural) method, resulting in the following problems with your code:

    1. The parameters are stored under the 'Parameters' key, not 'Parameter'
    2. The value is a list not a single dict

    In order to get the value, use either the get_parameter (singular) method or do something like this to print out the names and values of the parameters requested:

    for parameter in parameters.get('Parameters', []):
        print(parameter['Name'], '=', parameter['Value'])