

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 步骤 1：为自定义扩展程序创建 Lambda 函数 Amazon AppConfig
<a name="working-with-appconfig-extensions-creating-custom-lambda"></a>

对于大多数用例，要创建自定义扩展，必须创建一个 Amazon Lambda 函数来执行扩展中定义的任何计算和处理。本节包括自定义 Amazon AppConfig 扩展的 Lambda 函数示例代码。本部分还包括有效负载请求和响应参考详细信息。有关创建 Lambda 函数的更多信息，请参阅 *Amazon Lambda 开发人员指南*中的 [Lambda 入门](https://docs.amazonaws.cn/lambda/latest/dg/getting-started.html)。

## 代码示例
<a name="working-with-appconfig-extensions-creating-custom-lambda-code-sample"></a>

以下 Lambda 函数的示例代码在调用时会自动将 Amazon AppConfig 配置备份到 Amazon S3 存储桶。每当创建或部署新配置时，都会备份该配置。该示例使用扩展程序参数，因此不必在 Lambda 函数中对存储桶名称进行硬编码。通过使用扩展程序参数，用户可以将扩展程序附加到多个应用程序，并将配置备份到不同的存储桶。代码示例包含用于进一步解释该函数的注释。

**扩展程序的 Lambda 函数示例 Amazon 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)
```

如果要在本演练中使用此示例，请使用名称 **MyS3ConfigurationBackUpExtension** 保存它，并复制该函数的 Amazon 资源名称（ARN）。在下一节中创建 Amazon Identity and Access Management (IAM) 代入角色时，您将指定 ARN。您可以在创建扩展程序时指定 ARN 和名称。

## 有效负载参考
<a name="working-with-appconfig-extensions-creating-custom-lambda-payload"></a>

本节包括使用自定义 Amazon AppConfig 扩展程序的有效载荷请求和响应参考详细信息。

**请求结构**  
*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'
}
```

**请求结构**  
*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'
}
```

**异步事件**  


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

**响应结构**  
以下示例显示了您的 Lambda 函数在响应自定义 Amazon AppConfig 扩展程序的请求时返回的内容。

*PRE\$1\$1 同步事件 - 成功响应*

如果要转换内容，请使用以下命令：

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

*AT\$1\$1 同步事件 - 成功响应*

如果您想控制部署的后续步骤（继续部署或回滚部署），请在响应中设置 `Directive` 和 `Description` 属性。

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

`Directive` 支持两个值：`CONTINUE` 或 `ROLL_BACK`。在您的有效载荷响应中使用这些枚举来控制部署的后续步骤。

*同步事件 - 成功响应*

如果要转换内容，请使用以下命令：

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

如果不想转换内容，则不返回任何内容。

*异步事件 - 成功响应*

无返回内容。

*所有错误事件*

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