Introduction#

  • Create a IAM role in a stack and export its name
  • Refer the IAM role in another stack
  • Stack name provided at run time aws cloudformation create-stack

IAM Role#

AWSTemplateFormatVersion: 2010-09-09
Description: "iam role for a lambda function"
Resources:
LambdaExecutionRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- "sts:AssumeRole"
Path: /demo/logaccess/
Policies:
- PolicyName: root
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: "arn:aws:logs:*:*:*"
Outputs:
LambdaExecutionRoleArn:
Value: !GetAtt LambdaExecutionRole.Arn
Export:
Name:
Fn::Sub: ${AWS::StackName}-LambdaExecutionRoleArn
LambdaExecutionRoleName:
Value: !Ref LambdaExecutionRole
Export:
Name:
Fn::Sub: ${AWS::StackName}-LambdaExecutionRoleName

Lambda Function#

AWSTemplateFormatVersion: 2010-09-09
Description: "a lambda function"
Parameters:
LambdaRoleStackName:
Type: String
Description: "The name of the stack that created the lambda execution role"
Default: "cfn-lambda-role-demo"
Resources:
LambdaFunction:
Type: AWS::Lambda::Function
Properties:
Handler: "index.handler"
Role:
Fn::ImportValue:
Fn::Sub: ${LambdaRoleStackName}-LambdaExecutionRoleArn
Code:
ZipFile: |
import json
def handler(event, context):
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Runtime: "python3.10"
Timeout: 30
Outputs:
LambdaFunctionArn:
Value: !GetAtt LambdaFunction.Arn
Export:
Name: LambdaFunctionArn

Deploy#

aws cloudformation validate-template \
--template-body file://role.yaml
aws cloudformation create-stack \
--stack-name cfn-lambda-role-demo \
--template-body file://role.yaml \
--capabilities CAPABILITY_NAMED_IAM
aws cloudformation create-stack \
--stack-name cfn-lambda-demo \
--template-body file://lambda.yaml \
--capabilities CAPABILITY_NAMED_IAM
aws cloudformation update-stack \
--stack-name cfn-lambda-demo \
--template-body file://lambda.yaml \
--capabilities CAPABILITY_NAMED_IAM
aws cloudformation delete-stack \
--stack-name cfn-demo-demo

Reference#

  • iam path