Skip to content

Instantly share code, notes, and snippets.

@pwmcintyre
Last active January 22, 2020 09:22
Show Gist options
  • Save pwmcintyre/3724d1c1addbdf593225990f6f6700c1 to your computer and use it in GitHub Desktop.
Save pwmcintyre/3724d1c1addbdf593225990f6f6700c1 to your computer and use it in GitHub Desktop.
sample lambda cloudformation

Sample Lambda

Example IAM Role + Lambda

This will fail, you'll need to fix it somehow!

Commands

setup

export \
    AWS_PROFILE=nbos-sandbox \
    AWS_REGION=us-west-2 \
    STACK_NAME=sample-lambda-${RANDOM}

deploy

aws --profile ${AWS_PROFILE} --region ${AWS_REGION} cloudformation deploy \
    --stack-name ${STACK_NAME} \
    --template-file cloudformation.yaml \
    --capabilities CAPABILITY_IAM

invoke

FUNCTION_NAME=$(aws --profile ${AWS_PROFILE} --region ${AWS_REGION} cloudformation describe-stacks \
    --stack-name ${STACK_NAME} \
    --output text \
    --query "Stacks[0].Outputs[?OutputKey == 'ExampleFunction']. OutputValue")

aws --profile ${AWS_PROFILE} --region ${AWS_REGION} lambda invoke \
    --payload '{ "foo": "bar" }' \
    --function-name ${FUNCTION_NAME} \
    _out.json

tear down

BUCKET_NAME=$(aws --profile ${AWS_PROFILE} --region ${AWS_REGION} cloudformation describe-stacks \
    --stack-name ${STACK_NAME} \
    --output text \
    --query "Stacks[0].Outputs[?OutputKey == 'ExampleBucket']. OutputValue")

aws --profile ${AWS_PROFILE} --region ${AWS_REGION} s3 rb s3://${BUCKET_NAME} --force

aws --profile ${AWS_PROFILE} --region ${AWS_REGION} cloudformation delete-stack \
    --stack-name ${STACK_NAME}

troubleshooting

assuming-role to imitate your application role

example ~/.aws/config

[profile lambda]
role_arn = arn:aws:iam::631042910881:role/example-lambda/example-lambda-ExampleLambdaExecutionRole-555W089C0550
source_profile = nbos-sandbox

test it

AWS_PROFILE=lambda aws whoami

... or

AWS_PROFILE=lambda aws s3 cp cloudformation.yaml s3://sample-lambda-12156-examplebucket-uevbfk47h3on/

run it locally

JavaScript SDK default credential provider doesn't use source_profile aws/aws-sdk-js#1064

instead -- you can use this (use this only locally)

import * as AWS from "aws-sdk"
AWS.config.credentials = new AWS.ChainableTemporaryCredentials({
    params: {
        RoleArn: 'arn:aws:iam::453719517077:role/ris-dev-2-export-service-StartQueryFunctionRole-11YF9WSUGVA2H',
        RoleSessionName: "temp",
    }
})
AWSTemplateFormatVersion: 2010-09-09
Resources:
ExampleBucket:
Type: AWS::S3::Bucket
ExampleLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
Path: !Sub /${ AWS::StackName }/
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
AWS: !Ref AWS::AccountId
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: root
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- s3:GetObject
# - s3:PutObject
Resource:
- !Sub ${ ExampleBucket.Arn }/*
ExampleFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Role: !GetAtt ExampleLambdaExecutionRole.Arn
Code:
ZipFile: |
var S3 = require('aws-sdk/clients/s3')
var client = new S3()
var log = (...event) => console.log(JSON.stringify(event))
log({ level: "INFO", message: "cold start", bucket: process.env.BUCKET })
module.exports.handler = async (event, context) => {
log({ level: "DEBUG", message: "invoked", event, context })
return client.putObject({
Body: JSON.stringify(context),
Bucket: process.env.BUCKET,
Key: `${ context.awsRequestId }.json`,
}).promise()
}
Runtime: nodejs12.x
Environment:
Variables:
BUCKET: !Ref ExampleBucket
Outputs:
ExampleBucket:
Value: !Ref ExampleBucket
ExampleFunction:
Value: !Ref ExampleFunction
ExampleLambdaExecutionRoleArn:
Value: !GetAtt ExampleLambdaExecutionRole.Arn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment