Search code examples
amazon-web-servicesserverlesssam

workflow for testing lambda policies with aws SAM local


The aws SAM local documentation states that SAM Local will invoke functions with my locally configured IAM credentials.

I want to test a cloudformation template that consists of a Lambda function and a role attached to this function that grants access to delete the content of ONE SPECIFIC s3 bucket. The bucket name is both a template parameter, and an argument to the lambda function. (Not sure it matters, but I don't use the serverless transformations in the CFN template.)

I avoid testing this function with my admin profile, since a typo in the bucket name will delete all contents of the wrong bucket.

What is the suggested workflow to test such a function?

What I'm currently doing:

  • Create a temporary IAM user/group
  • attach the policy to be tested to this group
  • export the access environment variables before calling sam local invoke

Is there a quicker way to do this?


Solution

  • Invoke Lambda with DryRun

    Invoke the function with Dryrun to request AWS Lambda to not execute the function but do some verification, such as if the caller is authorized to invoke the function and if the inputs are valid.

    aws lambda invoke --function-name <name> --invocation-type DryRun
    

    Creating ChangeSets for Cloudformation: Change Sets = Dry Run Mode

    Create a changeset with "create-change-set" and review the changes in the Console UI or CLI and then apply the changes using execute changes using the CLI or UI.

    Create Changeset:

    aws cloudformation create-change-set --stack-name example --template-body file://templates/instance_and_route53.yml --parameters file://parameters/instance_and_route53.json --change-set-name changeset-1
    

    Execute Changeset

    aws cloudformation execute-change-set --stack-name example --change-set-name changeset-1