Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock ssm from boto3?

Tags:

pytest

boto3

moto

I tried moto, but I always get:

botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the GetParameter operation: The security token included in the request is invalid.

MVCE: test_example.py

import moto
import boto3


def ssm():
    boto3.setup_default_session()
    with moto.mock_ssm():
        ssm = boto3.client('ssm', region_name='us-east-1',
                           aws_access_key_id='testing',
                           aws_secret_access_key='testing')
        ssm.put_parameter(
            Name="/foo/bar",
            Description="A test parameter",
            Value="this is it!",
            Type="SecureString",
        )
        yield ssm


def get_ssm_param(ssm_parameter_name):
    session = boto3.Session()
    ssm_client = session.client("ssm")
    param = ssm_client.get_parameter(Name=ssm_parameter_name, WithDecryption=True)
    return param["Parameter"]["Value"]


def test_get_ssm_param():
    foo = get_ssm_param('/foo/bar')
    assert foo == "this is it!"

execute

pytest test_example.py

My System

moto==1.3.13
boto==2.49.0
boto3==1.9.201
botocore==1.12.201
like image 653
Martin Thoma Avatar asked Oct 17 '25 19:10

Martin Thoma


1 Answers

A co-worker showed me that this works:

from moto import mock_ssm
import boto3


def get_ssm_param(ssm_parameter_name):
    session = boto3.Session()
    ssm_client = session.client("ssm")
    param = ssm_client.get_parameter(Name=ssm_parameter_name, WithDecryption=True)
    return param["Parameter"]["Value"]

@mock_ssm
def test_get_ssm_param():
    ssm = boto3.client('ssm')
    ssm.put_parameter(
        Name="/foo/bar",
        Description="A test parameter",
        Value="this is it!",
        Type="SecureString",
    )
    foo = get_ssm_param('/foo/bar')
    assert foo == "this is it!"

But it breaks when you add the credentials to the boto3.client.

like image 87
Martin Thoma Avatar answered Oct 19 '25 12:10

Martin Thoma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!