Comment puis-je utiliser une importation de ressource CloudFormation pour créer une configuration de notification Amazon S3 pour Lambda dans un compartiment S3 existant ?

Lecture de 5 minute(s)
0

Je veux utiliser une configuration de notification Amazon Simple Storage Service (Amazon S3) pour Amazon Lambda AWS sur un compartiment S3 existant. Pour ce faire, j'utilise AWS CloudFormation pour importer une ressource.

Brève description

Pour configurer une notification Amazon S3 sans utiliser de ressource personnalisée, vous pouvez :

  1. Créez un modèle à l'aide de la fonction Lambda S3NotificationLambdaFunction. Cette fonction ajoute la configuration de notification existante du bucket NotificationS3Bucket.
  2. Utilisez une importation de ressources pour intégrer le compartiment NotificationS3Bucket S3 existant spécifié dans le modèle dans la gestion de CloudFormation.
  3. Mettez à jour la pile CloudFormation pour inclure les propriétés que vous souhaitez activer dans votre compartiment S3.

Pour utiliser une ressource personnalisée, consultez Comment puis-je créer une configuration de notification Amazon S3 pour Lambda sur un compartiment S3 existant en utilisant CloudFormation ?

Solution

Important : les étapes suivantes remplacent toutes les configurations de notification existantes ou créées manuellement dans un compartiment S3. Vous pouvez suivre ces étapes pour ajouter une nouvelle configuration de notification à un compartiment S3 importé.

Créer un modèle CloudFormation avec une fonction Lambda

L'exemple de modèle suivant crée une fonction Lambda, avec un rôle d'exécution et des autorisations pour appeler la fonction. Pour utiliser une fonction Lambda existante, utilisez la fonction Lambda Amazon Resource Name (ARN) dans votre modèle CloudFormation pour la propriété LambdaConfiguration dans le compartiment S3.

AWSTemplateFormatVersion: 2010-09-09
Description: >-
  Sample template that shows you how to import an existing S3 bucket as an event source for a Lambda function
Parameters:
  NotificationBucket:
    Type: String
    Description: S3 bucket that's used for Lambda event notification
Resources:
  S3NotificationLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Code:
        ZipFile: !Join
          - |+

          - - import json
            - 'def lambda_handler(event,context):'
            - '    return ''Welcome... This is a test Lambda Function'''
      Handler: index.lambda_handler
      Role: !GetAtt LambdaIAMRole.Arn
      Runtime: python3.6
      Timeout: 5
  LambdaInvokePermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
      FunctionName: !GetAtt S3NotificationLambdaFunction.Arn
      Action: 'lambda:InvokeFunction'
      Principal: s3.amazonaws.com
      SourceAccount: !Ref 'AWS::AccountId'
      SourceArn: !Sub 'arn:aws:s3:::${NotificationBucket}'
  LambdaIAMRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 's3:GetBucketNotification'
                  - 's3:PutBucketNotification'
                Resource: !Sub 'arn:aws:s3:::${NotificationBucket}'
              - Effect: Allow
                Action:
                  - 'logs:CreateLogGroup'
                  - 'logs:CreateLogStream'
                  - 'logs:PutLogEvents'
                Resource: 'arn:aws:logs:*:*:*'

Importer un compartiment S3 existant dans votre pile CloudFormation

1.    Ouvrez la console AWS CloudFormation.

2.    Dans le volet de navigation, choisissez Stack (Pile), puis sélectionnez la pile que vous avez créée précédemment.

3.    Choisissez Stack actions (Actions de pile), puis choisissez Import resources into stack (Importer des ressources dans la pile).

4.    Vérifiez la page Import overview (Vue d'ensemble de l'importation), puis choisissez Next (Suivant).

Important : dans votre modèle CloudFormation, chaque ressource que vous importez doit posséder un attribut DeletionPolicy, et toutes les autres ressources doivent rester identiques. Par exemple :

AWSTemplateFormatVersion: 2010-09-09
Description: >-
  Sample template that shows you how to import an existing S3 bucket as an event source for a Lambda function
Parameters:
  NotificationBucket:
    Type: String
    Description: S3 bucket that's used for Lambda event notification
Resources:
  S3NotificationLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      .
      .
  LambdaInvokePermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
      .
      .
  LambdaIAMRole:
    Type: 'AWS::IAM::Role'
    Properties:
      .
      .

  <The preceding resources were already created. Now, add the DeletionPolicy to the preceding stack to import the S3 bucket.>
  NotificationS3Bucket:
    Type: 'AWS::S3::Bucket'
    DeletionPolicy: Retain
    Properties:
      BucketName: myenv-bucket          #Bucket name to import

5.    Dans la section Specify template (Spécifier un modèle), choisissez URL Amazon S3 ou Upload a template file (Charger un fichier de modèle) en fonction de vos besoins, puis Next (Suivant).

6.    Suivez le reste des étapes de l'assistant pour importer vos ressources existantes. Pour plus d'informations, consultez Importer une ressource existante dans une pile à l'aide de la console AWS CloudFormation.

7.    Attendez que l'état de la pile soit IMPORT_COMPLETE.

Mettez à jour votre modèle CloudFormation

1.    Mettez à jour la pile avec le modèle CloudFormation que vous avez modifié précédemment.

2.    Attendez que l'état de la pile soit UPDATE_COMPLETE, puis vérifiez la NotificationConfiguration sur le compartiment S3.

3.    Activez les notifications d'événements Amazon S3 sur votre compartiment S3. Dans l'exemple de modèle suivant, le nom du compartiment est myenv-bucket :

AWSTemplateFormatVersion: 2010-09-09
Description: >-
  Sample template that shows you how to import an existing S3 bucket as an event source for a Lambda function
Parameters:
  NotificationBucket:
    Type: String
    Description: S3 bucket that's used for Lambda event notification
Resources:
  S3NotificationLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      .
      .
  LambdaInvokePermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
      .
      .
  LambdaIAMRole:
    Type: 'AWS::IAM::Role'
    Properties:
      .
      .

  <The preceding resources were already created. Now, add the DeletionPolicy to the preceding stack to import the S3 bucket.>
  NotificationS3Bucket:
    Type: 'AWS::S3::Bucket'
    DeletionPolicy: Retain
    Properties:
      BucketName: myenv-bucket
      NotificationConfiguration:   #Update stack with NotificationConfiguration
          LambdaConfigurations:
              - Event: 's3:ObjectCreated:Put'
                Function: !GetAtt S3NotificationLambdaFunction.Arn
              - Event: 's3:ObjectRemoved:*'
                Function: !GetAtt S3NotificationLambdaFunction.Arn

AWS OFFICIEL
AWS OFFICIELA mis à jour il y a un an