Skip to content

Instantly share code, notes, and snippets.

@mixja
Last active March 31, 2018 08:31
Show Gist options
  • Save mixja/66cdbd7283bb06d56ef5475ceb733bd6 to your computer and use it in GitHub Desktop.
Save mixja/66cdbd7283bb06d56ef5475ceb733bd6 to your computer and use it in GitHub Desktop.
Creating an S3 Stack using Lambda
# This is a CloudFormation definition of the IAM role required for the CloudFormation Service
# This must include permissions to create/update/delete any resources defined in the stack
CloudFormationServiceRole:
Type: AWS::IAM::Role
Properties:
RoleName: cfn-s3-deployer
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service: cloudformation.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonS3FullAccess
import os, logging, datetime, json
import boto3
# Configure logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(os.environ.get('LOG_LEVEL','INFO'))
def format_json(data):
return json.dumps(data, default=lambda d: d.isoformat() if isinstance(d, datetime.datetime) else str(d))
# Clients
# Refer to http://boto3.readthedocs.io/en/latest/reference/services/cloudformation.html#client for API docs
client = boto3.client('cloudformation')
# Settings
S3_URL = os.environ.get('S3_URL', 'https://s3.amazonaws.com/341356192351-cfn-templates/ping.yml')
STACK_NAME = os.environ.get('STACK_NAME', 'ping')
ROLE_ARN = os.environ.get('ROLE_ARN', 'arn:aws:iam::158949774536:role/cfn-s3-deployer')
def lambda_handler(event, context):
log.info("Received event: %s" % format_json(event))
# TODO: Process and validate event
# TODO: Check stack if already exists and what state it is in
# response = client.describe_stacks(
# StackName=STACK_NAME
# )
# Create stack
try:
response = client.create_stack(
StackName=STACK_NAME,
TemplateURL=S3_URL,
Capabilities=['CAPABILITY_NAMED_IAM'],
RoleARN=ROLE_ARN
)
log.info("Stack creation initiated successfully for stack %s" % response['StackId'])
# Return Lex success result
return {'result': 'success'}
except Exception as e:
log.error("An error occurred: %s" % e)
# Return Lex failure result
return {'result': 'failed'}
# This is a CloudFormation definition of the IAM role required for the Lambda Function
LambdaFunctionRole:
Type: AWS::IAM::Role
Properties:
RoleName: lambda-function-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Policies:
- PolicyName: LambdaFunctionPermissions
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: CloudFormationPermissions
Effect: Allow
Action: cloudformation:CreateStack
Resource: arn:aws:cloudformation:us-east-1:158949774536:stack/ping/*
- Sid: S3TemplateAccess
Effect: Allow
Action: s3:*
Resource:
- arn:aws:s3:::341356192351-cfn-templates
- arn:aws:s3:::341356192351-cfn-templates/*
- Sid: PassRoleToCloudFormationService
Effect: Allow
Action: iam:PassRole
Resource: arn:aws:iam::158949774536:role/cfn-s3-deployer
- Sid: CloudWatchLogs
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
{
"currentIntent": {
"slots": {
"PickupDate": "2030-11-08",
"PickupTime": "10:00",
"FlowerType": "lilies"
},
"name": "OrderFlowers",
"confirmationStatus": "None"
},
"bot": {
"alias": "$LATEST",
"version": "$LATEST",
"name": "OrderFlowers"
},
"userId": "John",
"invocationSource": "DialogCodeHook",
"outputDialogMode": "Text",
"messageVersion": "1.0",
"sessionAttributes": {}
}
AWSTemplateFormatVersion: "2010-09-09"
Description: AWS CloudFormation Starter Template
Parameters:
MyStackInput:
Type: Number
Description: A random number
Default: 10000
Resources:
StarterBucket:
Type: "AWS::S3::Bucket"
Properties:
BucketName:
Fn::Sub: ${AWS::AccountId}-starter-bucket-${MyStackInput}
Tags:
- Key: Name
Value:
Fn::Sub: ${AWS::AccountId}-starter-bucket-${MyStackInput}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment