could I write some code in cloudformation template?

0

I write some code in cloudformation template,but away wrong, can you tell me why?

    MyS3Bucket:
        Type: AWS::S3::Bucket
        Properties:
            BucketName: test
        DeletionPolicy: Retain

    LambdaExecutionRole:
        Type: AWS::IAM::Role
        Properties:
            AssumeRolePolicyDocument:
                Version: '2012-10-17'
                Statement:
                    - Effect: Allow
                      Principal:
                          Service: lambda.amazonaws.com
                      Action: sts:AssumeRole
            ManagedPolicyArns:
                - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
            Path: /
        DeletionPolicy: Retain

    LambdaFunction:
        Type: AWS::Lambda::Function
        Properties:
            FunctionName: MyS3CopyFunction
            Runtime: python3.8
            Role: !GetAtt LambdaExecutionRole.Arn
            Handler: index.lambda_handler
            Code:
                ZipFile: !Join 
                  - |+

                  - - import boto3

                    - 'def lambda_handler(event, context):'
                    - '    source_bucket = setting-params'
                    - '    destination_bucket = test'
                    - '    s3 = boto3.client('s3')'
                    - '    s3.Object(destination_bucket).copy_from(CopySource=f"{source_bucket}")'

            Timeout: 30
        DeletionPolicy: Retain

    S3EventTrigger:
        Type: AWS::Lambda::EventSourceMapping
        Properties:
            BatchSize: 1
            EventSourceArn: !GetAtt SettingParams.Arn
            FunctionName: !Ref LambdaFunction
        DeletionPolicy: Retain
profile picture
Dgk
asked 9 months ago250 views
1 Answer
0

Hi,

to inline your Lambda code directly in the CloudFormation template, follow this example https://github.com/aws-samples/aws-cloudformation-inline-python-lambda-example/blob/main/base-cfn-lambda.yml from this repo https://github.com/aws-samples/aws-cloudformation-inline-python-lambda-example

.....

Code:
        ZipFile: |
            # Imports
            import os
            import boto3
            import botocore
            import logging
            import random
            import string

            # Set up clients and resources
            ddbclient = boto3.client('dynamodb')

            # Set up the logger
            logger = logging.getLogger()
            logger.setLevel(logging.INFO)
            #logger.setLevel(logging.DEBUG) # Very verbose

            # Env variables from CFN
            tablename = os.environ.get('TableName')
            keyname = os.environ.get('KeyName')

            def lambda_handler(event, context):
                # Generate a random string to ensure no duplicates are put into DDB table
                randomstring = (''.join(random.choice(string.ascii_letters) for i in range(10)))
                logger.info('Random string generated: %s', randomstring)
                
                def ddb_client(tablename, keyname, stringdata):
                    response = ddbclient.put_item(
                    Item={
                        keyname: {
                            'S': stringdata
                        }
                    },
                    ReturnConsumedCapacity='TOTAL',
                    TableName=tablename
                    )
                    return(response)
                
                try:    
                    ddb_response = ddb_client(tablename, keyname, randomstring)
                    logger.info(ddb_response)
                except botocore.exceptions.ClientError as error:
                    # Put your error handling logic here
                    raise error
                    
                return(ddb_response)
    
  DynamoDBTable:
    Type: AWS::DynamoDB::Table

......

Hope it helps, Didier

profile pictureAWS
EXPERT
answered 9 months ago
  • thanks for your answer,I want know how to real-time monitoring of A bucket, copying files to B bucket while adding them to A bucket ,and when I build a new environment I want copy A bucket's object to B bucket. and how to create tables and indexes for DocumentDB by CloudFormat and Lambda Function.I can hardly find any information for this two questions.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions