

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Étape 1 : Création d'une fonction Lambda pour une extension personnalisée AWS AppConfig
<a name="working-with-appconfig-extensions-creating-custom-lambda"></a>

Dans la plupart des cas d'utilisation, pour créer une extension personnalisée, vous devez créer une AWS Lambda fonction pour effectuer les calculs et les traitements définis dans l'extension. Cette section inclut un exemple de code de fonction Lambda pour une extension personnalisée AWS AppConfig . Cette section inclut également les détails de référence des demandes de charge utile et des réponses. *Pour plus d'informations sur la création d'une fonction Lambda, voir [Getting started with Lambda](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html) dans le manuel du développeur.AWS Lambda *

## Exemple de code
<a name="working-with-appconfig-extensions-creating-custom-lambda-code-sample"></a>

L'exemple de code suivant pour une fonction Lambda, lorsqu'elle est invoquée, sauvegarde automatiquement une AWS AppConfig configuration dans un compartiment Amazon S3. La configuration est sauvegardée chaque fois qu'une nouvelle configuration est créée ou déployée. L'exemple utilise des paramètres d'extension afin que le nom du compartiment n'ait pas besoin d'être codé en dur dans la fonction Lambda. En utilisant les paramètres d'extension, l'utilisateur peut associer l'extension à plusieurs applications et sauvegarder les configurations dans différents buckets. L'exemple de code inclut des commentaires pour expliquer plus en détail la fonction.

**Exemple de fonction Lambda pour une extension AWS AppConfig **

```
from datetime import datetime
import base64
import json

import boto3


def lambda_handler(event, context):
    print(event)
    
    # Extensions that use the PRE_CREATE_HOSTED_CONFIGURATION_VERSION and PRE_START_DEPLOYMENT 
    # action points receive the contents of AWS AppConfig configurations in Lambda event parameters.
    # Configuration contents are received as a base64-encoded string, which the lambda needs to decode 
    # in order to get the configuration data as bytes. For other action points, the content 
    # of the configuration isn't present, so the code below will fail.
    config_data_bytes = base64.b64decode(event["Content"])
    
    # You can specify parameters for extensions. The CreateExtension API action lets you define  
    # which parameters an extension supports. You supply the values for those parameters when you 
    # create an extension association by calling the CreateExtensionAssociation API action.
    # The following code uses a parameter called S3_BUCKET to obtain the value specified in the 
    # extension association. You can specify this parameter when you create the extension 
    # later in this walkthrough.
    extension_association_params = event.get('Parameters', {})
    bucket_name = extension_association_params['S3_BUCKET']
    write_backup_to_s3(bucket_name, config_data_bytes)
    
    # The PRE_CREATE_HOSTED_CONFIGURATION_VERSION and PRE_START_DEPLOYMENT action points can 
    # modify the contents of a configuration. The following code makes a minor change 
    # for the purposes of a demonstration.
    old_config_data_string = config_data_bytes.decode('utf-8')
    new_config_data_string = old_config_data_string.replace('hello', 'hello!')
    new_config_data_bytes = new_config_data_string.encode('utf-8')
    
    # The lambda initially received the configuration data as a base64-encoded string 
    # and must return it in the same format.
    new_config_data_base64string = base64.b64encode(new_config_data_bytes).decode('ascii')
    
    return {
        'statusCode': 200,
        # If you want to modify the contents of the configuration, you must include the new contents in the 
        # Lambda response. If you don't want to modify the contents, you can omit the 'Content' field shown here.
        'Content': new_config_data_base64string
    }


def write_backup_to_s3(bucket_name, config_data_bytes):
    s3 = boto3.resource('s3')
    new_object = s3.Object(bucket_name, f"config_backup_{datetime.now().isoformat()}.txt")
    new_object.put(Body=config_data_bytes)
```

Si vous souhaitez utiliser cet exemple au cours de cette procédure pas à pas, enregistrez-le sous le nom **MyS3ConfigurationBackUpExtension** et copiez l'Amazon Resource Name (ARN) de la fonction. Vous spécifiez l'ARN lorsque vous créez le rôle Gestion des identités et des accès AWS (IAM) assume dans la section suivante. Vous spécifiez l'ARN et le nom lorsque vous créez l'extension.

## Référence de charge utile
<a name="working-with-appconfig-extensions-creating-custom-lambda-payload"></a>

Cette section inclut les informations de référence relatives aux demandes de charge utile et aux réponses pour travailler avec des AWS AppConfig extensions personnalisées.

**Structure de la demande**  
*AtDeploymentTick*

```
{
    'InvocationId': 'o2xbtm7',
    'Parameters': {
        'ParameterOne': 'ValueOne',
        'ParameterTwo': 'ValueTwo'
    },
    'Type': 'OnDeploymentStart',
    'Application': {
        'Id': 'abcd123'
    },
    'Environment': {
        'Id': 'efgh456'
    },
    'ConfigurationProfile': {
        'Id': 'ijkl789',
        'Name': 'ConfigurationName'
    },
    'DeploymentNumber': 2,
    'Description': 'Deployment description',
    'ConfigurationVersion': '2',
    'DeploymentState': 'DEPLOYING',
    'PercentageComplete': '0.0'
}
```

**Structure de la demande**  
*PreCreateHostedConfigurationVersion*

```
{
    'InvocationId': 'vlns753', // id for specific invocation
    'Parameters': {
        'ParameterOne': 'ValueOne',
        'ParameterTwo': 'ValueTwo'
    },
    'ContentType': 'text/plain',
    'ContentVersion': '2',
    'Content': 'SGVsbG8gZWFydGgh', // Base64 encoded content
    'Application': {
        'Id': 'abcd123',
        'Name': 'ApplicationName'
    },
    'ConfigurationProfile': {
        'Id': 'ijkl789',
        'Name': 'ConfigurationName'
    },
    'Description': '',
    'Type': 'PreCreateHostedConfigurationVersion',
    'PreviousContent': {
        'ContentType': 'text/plain',
        'ContentVersion': '1',
        'Content': 'SGVsbG8gd29ybGQh'
    }
}
```

*PreStartDeployment*

```
{
    'InvocationId': '765ahdm',
    'Parameters': {
        'ParameterOne': 'ValueOne',
        'ParameterTwo': 'ValueTwo'
    },
    'ContentType': 'text/plain',
    'ContentVersion': '2',
    'Content': 'SGVsbG8gZWFydGgh',
    'Application': {
        'Id': 'abcd123',
        'Name': 'ApplicationName'
    },
    'Environment': {
        'Id': 'ibpnqlq',
        'Name': 'EnvironmentName'
    },
    'ConfigurationProfile': {
        'Id': 'ijkl789',
        'Name': 'ConfigurationName'
    },
    'DeploymentNumber': 2,
    'Description': 'Deployment description',
    'Type': 'PreStartDeployment'
}
```

**Événements asynchrones**  


*OnStartDeployment, OnDeploymentStep, OnDeployment*

```
{
    'InvocationId': 'o2xbtm7',
    'Parameters': {
        'ParameterOne': 'ValueOne',
        'ParameterTwo': 'ValueTwo'
    },
    'Type': 'OnDeploymentStart',
    'Application': {
        'Id': 'abcd123'
    },
    'Environment': {
        'Id': 'efgh456'
    },
    'ConfigurationProfile': {
        'Id': 'ijkl789',
        'Name': 'ConfigurationName'
    },
    'DeploymentNumber': 2,
    'Description': 'Deployment description',
    'ConfigurationVersion': '2'
}
```

**Structure de réponse**  
Les exemples suivants montrent ce que renvoie votre fonction Lambda en réponse à la demande d'une extension personnalisée AWS AppConfig .

*PRE\_\* Evénements synchrones - réponse réussie*

Si vous souhaitez transformer le contenu, utilisez ce qui suit :

```
"Content": "SomeBase64EncodedByteArray"
```

*AT\_\* Evénements synchrones - réponse réussie*

Si vous souhaitez contrôler les étapes suivantes d'un déploiement (poursuivre un déploiement ou l'annuler), définissez `Directive` et `Description` attributs dans la réponse. 

```
"Directive": "ROLL_BACK"
"Description" "Deployment event log description"
```

`Directive`prend en charge deux valeurs : `CONTINUE` ou`ROLL_BACK`. Utilisez ces énumérations dans votre réponse à la charge utile pour contrôler les prochaines étapes d'un déploiement.

*Événements synchrones - réponse réussie*

Si vous souhaitez transformer le contenu, utilisez ce qui suit :

```
"Content": "SomeBase64EncodedByteArray"
```

Si vous ne souhaitez pas transformer le contenu, ne renvoyez rien.

*Événements asynchrones - réponse réussie*

Ne rien retourner.

*Tous les événements d'erreur*

```
{
        "Error": "BadRequestError",
        "Message": "There was malformed stuff in here",
        "Details": [{
            "Type": "Malformed",
            "Name": "S3 pointer",
            "Reason": "S3 bucket did not exist"
        }]
    }
```