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-09Description: "iam role for a lambda function"Resources:LambdaExecutionRole:Type: "AWS::IAM::Role"Properties:AssumeRolePolicyDocument:Version: 2012-10-17Statement:- Effect: AllowPrincipal:Service:- lambda.amazonaws.comAction:- "sts:AssumeRole"Path: /demo/logaccess/Policies:- PolicyName: rootPolicyDocument:Version: 2012-10-17Statement:- Effect: AllowAction:- "logs:CreateLogGroup"- "logs:CreateLogStream"- "logs:PutLogEvents"Resource: "arn:aws:logs:*:*:*"Outputs:LambdaExecutionRoleArn:Value: !GetAtt LambdaExecutionRole.ArnExport:Name:Fn::Sub: ${AWS::StackName}-LambdaExecutionRoleArnLambdaExecutionRoleName:Value: !Ref LambdaExecutionRoleExport:Name:Fn::Sub: ${AWS::StackName}-LambdaExecutionRoleName
Lambda Function#
AWSTemplateFormatVersion: 2010-09-09Description: "a lambda function"Parameters:LambdaRoleStackName:Type: StringDescription: "The name of the stack that created the lambda execution role"Default: "cfn-lambda-role-demo"Resources:LambdaFunction:Type: AWS::Lambda::FunctionProperties:Handler: "index.handler"Role:Fn::ImportValue:Fn::Sub: ${LambdaRoleStackName}-LambdaExecutionRoleArnCode:ZipFile: |import jsondef handler(event, context):return {'statusCode': 200,'body': json.dumps('Hello from Lambda!')}Runtime: "python3.10"Timeout: 30Outputs:LambdaFunctionArn:Value: !GetAtt LambdaFunction.ArnExport:Name: LambdaFunctionArn
Deploy#
aws cloudformation validate-template \--template-body file://role.yamlaws cloudformation create-stack \--stack-name cfn-lambda-role-demo \--template-body file://role.yaml \--capabilities CAPABILITY_NAMED_IAMaws cloudformation create-stack \--stack-name cfn-lambda-demo \--template-body file://lambda.yaml \--capabilities CAPABILITY_NAMED_IAMaws cloudformation update-stack \--stack-name cfn-lambda-demo \--template-body file://lambda.yaml \--capabilities CAPABILITY_NAMED_IAMaws cloudformation delete-stack \--stack-name cfn-demo-demo