Boto3 AWS API error responses for SSM

Question:

I am using a simple boto3 script to retrieve a parameter from SSM param store in my aws account. The python script looks like below:

client = get_boto3_client('ssm', 'us-east-1')
try:
    response = client.get_parameter(Name='my_param_name',WithDecryption=True)
except Exception as e:
    logging.error("retrieve param error: {0}".format(e))
    raise e
return response

If the given parameter is not available, I get a generic error in the response like below:

 An error occurred (ParameterNotFound) when calling the GetParameter operation: Parameter my_param_name not found.   

I have verified method signature from boto3 ssm docs. Related AWS API Docs confirms to return a 400 response when parameter does not exist in the param store.

My question is that how do I verify if the exception caught in the response is actually a 400 status code so that I can handle it accordingly.

Asked By: Vishal

||

Answers:

You can try catching client.exceptions.ParameterNotFound:

client = get_boto3_client('ssm', 'us-east-1')

try:
  response = client.get_parameter(Name='my_param_name',WithDecryption=True)
except client.exceptions.ParameterNotFound:
  logging.error("not found")
Answered By: kichik

You can look at the status via response[‘Error’][‘Code’], but since there are multiple reasons for a 400, I would recommend a better approach:

response = client.get_parameter(Name='my_param_name',WithDecryption=True)

if 'Parameters' not in response:
    raise ValueError('Response did not contain parameters key')
else:
    return response
Answered By: Aphid

Catching exceptions is not always a good idea. For those who would like to avoid it, use get-parameters instead and check if your parameter is in InvalidParameters:

client = get_boto3_client('ssm', 'us-east-1')

def get_ssm_parameter(name):
    parameters = client.get_parameters(Names=[name], WithDecryption=True)
    invalid_parameters = parameters.get('InvalidParameters')
    if invalid_parameters and name in invalid_parameters:
        return None
    return parameters['Parameters'][0]
Answered By: elshev