Setting up an AWS Lambda function with an IAM role using AWS CloudFormation

To set up an AWS Lambda function using AWS CloudFormation, with an IAM role, you can use the AWS::IAM::Role and AWS::Lambda::Function resources. Here is an example of how you might use these resources in a CloudFormation template:

Resources:
  MyIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: MyPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - s3:ListBucket
                Resource: arn:aws:s3:::my-bucket
  MyFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          def handler(event, context):
            return "Hello, World!"
      Handler: index.handler
      Role: !GetAtt MyIAMRole.Arn
      Runtime: python3.8
      Timeout: 30

This will create an IAM role (MyIAMRole) with a policy that allows the Lambda function to list the objects in the my-bucket S3 bucket. It will also create a Lambda function (MyFunction) that runs a Python 3.8 runtime and has a 30-second timeout. The function code is specified using a `Zip

ALSO READ  Setting Up an S3 Trigger for an AWS Lambda Function in the AWS Clouformation

Abhay Singh

I'm Abhay Singh, an Architect with 9 Years of It experience. AWS Certified Solutions Architect.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *