

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Etapa 1: criar uma função Lambda para uma extensão personalizada AWS AppConfig
<a name="working-with-appconfig-extensions-creating-custom-lambda"></a>

Para a maioria dos casos de uso, para criar uma extensão personalizada, você deve criar uma AWS Lambda função para realizar qualquer computação e processamento definidos na extensão. Esta seção inclui um exemplo de código da função Lambda para uma extensão personalizada AWS AppConfig . Esta seção inclui também detalhes de referência de solicitações e respostas de carga útil. Para obter mais informações sobre como criar uma função do Lambda, consulte a seção [Conceitos básicos do Lambda](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html) no *Guia do desenvolvedor do AWS Lambda *.

## Código de exemplo
<a name="working-with-appconfig-extensions-creating-custom-lambda-code-sample"></a>

O código de exemplo a seguir para uma função Lambda, quando invocado, faz backup automático de uma AWS AppConfig configuração em um bucket do Amazon S3. O backup da configuração é feito sempre que uma nova configuração é criada ou implantada. O exemplo usa parâmetros de extensão para que o nome do bucket não precise ser codificado na função do Lambda. Usando parâmetros de extensão, o usuário pode anexar a extensão a vários aplicativos e fazer backup das configurações em diferentes buckets. O exemplo de código inclui comentários para explicar melhor a função.

**Exemplo de função Lambda para uma extensão 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)
```

Se você desejar usar esse exemplo durante este passo a passo, salve-o com o nome **MyS3ConfigurationBackUpExtension** e copie o nome do recurso da Amazon (ARN) da função. Você especifica o ARN ao criar a função de assumir AWS Identity and Access Management (IAM) na próxima seção. Você especifica o ARN e o nome ao criar a extensão.

## Referência de carga útil
<a name="working-with-appconfig-extensions-creating-custom-lambda-payload"></a>

Esta seção inclui detalhes de referência de solicitação e resposta de carga útil para trabalhar com AWS AppConfig extensões personalizadas.

**Estrutura de solicitações**  
*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'
}
```

**Estrutura de solicitações**  
*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'
}
```

**Eventos assíncronos**  


*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'
}
```

**Estrutura de respostas**  
Os exemplos a seguir mostram o que sua função Lambda retorna em resposta à solicitação de uma extensão personalizada AWS AppConfig .

*Eventos síncronos PRE\$1\$1: resposta bem-sucedida*

Se você deseja transformar o conteúdo, use o seguinte:

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

*Eventos síncronos AT\$1\$1: resposta bem-sucedida*

Se você quiser controlar as próximas etapas de uma implantação (continuar uma implantação ou revertê-la), defina os atributos `Directive` e `Description` na resposta. 

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

A `Directive` oferece suporte a dois valores: `CONTINUE` ou `ROLL_BACK`. Use esses enums na sua resposta de carga útil para controlar as próximas etapas de uma implantação.

*Eventos síncronos: resposta bem-sucedida*

Se você deseja transformar o conteúdo, use o seguinte:

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

Se você não deseja transformar o conteúdo, não retorne nada.

*Eventos assíncronos: resposta bem-sucedida*

Não retorne nada.

*Todos os eventos de erro*

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