Support using fake service with `aws-sam-local`
My application uses S3Client provided by AWS SDK. So I want to use fake object instead of actual S3 bucket to SDK when the testing with aws-sam-local. To realize this, we need to start some fake objects like fake-s3, localstack and set the endpoints of these to sdk endpoints.
However, aws-sam-local execute Lambda function in Docker container, so we need to access fake objects running on the host from the lambda container. But we cannot link any container to the lambda container or pass some options for lambda container running command.
Do you have any idea to help this situation ? If we cannot use aws-sam-local with the case like this at the moment, is there any plan to support the case like this ?
So you want to use SAM Local with localstack - https://github.com/localstack/localstack? AFAIK this doesn't work out of the box. We have to do some work in this CLI tool to allow the Docker container have access to ports exposed by localstack.
I would consider this as a feature request.
You can make it work if you run localstack in "infra" mode and access the endpoint using your local IP.
git clone https://github.com/localstack/localstack.git
cd localstack
make infra
Then you can create a Lambda function, e.g. lambda.py
if os.getenv('AWS_SAM_LOCAL'):
CLOUDWATCH = boto3.client('cloudwatch', endpoint_url='http://192.168.0.133:4582')
else:
CLOUDWATCH = boto3.client('cloudwatch')
...
def dynamodb_stream(event, context):
CLOUDWATCH.put_metric_data(
MetricData=[{
'MetricName':'TestMetric',
'Dimentions':[],
'Unit':'Count',
'Value':1.0
}],
Namespace='TestApp')
With a template of
AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: |
An example Serverless project
Resources:
dynamodb_stream:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.6
Handler: lambda.dynamodb_stream
Timeout: 300
And invoking sam should just work
sam local generate-event dynamodb | sam local invoke dynamodb_stream
Another solution is to partition your localstack and other containers onto a private docker network. This is probably a good idea anyway to keep your test containers from interfering or otherwise communicating with other docker containers or the host. You can use the sam local --docker-network option to achieve this. Works out of the box because all containers in a private network are automatically linked by docker. Just make sure your create your private docker network first (like when you launch localstack) because otherwise sam local will complain the network does not exist, as it does not auto-create private networks.
Going to close this issue because it didn't get much traction.