AWSTemplateFormatVersion: '2010-09-09' Description: This template creates an Lambda with related IAM roles and permissions. Parameters: LambdaFunctionName: Type: String AllowedPattern: "[a-zA-Z0-9]+[a-zA-Z0-9-]+[a-zA-Z0-9]+" Default: resource-auto-tagger S3BucketName: AllowedPattern: ^[0-9a-zA-Z]+([0-9a-zA-Z-.]*[0-9a-zA-Z])*$ ConstraintDescription: Bucket name can include numbers, lowercase letters, uppercase letters, periods (.), and hyphens (-). It cannot start or end with a hyphen (-). Description: S3 bucket name for the Lambda code. S3 bucket name can include numbers, lowercase letters, uppercase letters, and hyphens (-). It cannot start or end with a hyphen (-). Type: String LambdaFileName: AllowedPattern: ^[0-9a-zA-Z]+([0-9a-zA-Z-.]*[0-9a-zA-Z])*$ Description: File name for your lambda code with extension Type: String Resources: lambdaFunction: Type: AWS::Lambda::Function Properties: Code: "S3Bucket": !Ref S3BucketName "S3Key": !Ref LambdaFileName Description: Lambda function that will receive the event and add tags to EC2s FunctionName: !Ref LambdaFunctionName Handler: !Sub ${LambdaFunctionName}.lambda_handler MemorySize: 128 Role: !GetAtt lambdaIAMRole.Arn Runtime: python3.9 lambdaIAMRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Action: - sts:AssumeRole Effect: Allow Principal: Service: - lambda.amazonaws.com Policies: - PolicyName: Resource-auto-tagger-lambda-permissions-policy PolicyDocument: Version: 2012-10-17 Statement: - Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:DescribeLogStreams - logs:DescribeLogGroups Effect: Allow Resource: - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/* - Action: - logs:PutLogEvents - logs:GetLogEvents Effect: Allow Resource: - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:* - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*:log-stream:* - Action: - cloudwatch:PutMetricData - ec2:DescribeInstances - ec2:DescribeTags - ec2:CreateTags Effect: Allow Resource: "*" lambdaLogGroup: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub /aws/lambda/${LambdaFunctionName} RetentionInDays: 90 Outputs: lambdaArn: Value: !GetAtt lambdaFunction.Arn RoleArn: Description: Arn of Created Role Value: !GetAtt lambdaIAMRole.Arn