

# Lambda function example for the AWS AppConfig extension in AWS Systems Manager Cloud Extensions

The following example in Python reads a configuration and a feature flag through the extension in an AWS Lambda function. The function sends the same kinds of requests to `localhost:5333` as the examples in [HTTP client examples for the AWS AppConfig extension in AWS Systems Manager Cloud Extensions](cloud-extensions-ext-appconfig-http-examples.md). It uses only the Python standard library, so it needs no layer other than the Cloud Extensions runtime.

Before you begin, complete the following tasks:
+ Install the Cloud Extensions runtime as a layer of your function. To choose the profile that the runtime loads, set the `AWS_CLOUDEXTENSIONS_PROFILE` environment variable of the function to the profile name or ID.
+ Add the AWS AppConfig extension to that profile, with the extension identifier `aws:appconfig`, and approve the `appconfigdata` capability. For the steps, see [Adding the extension to a profile](cloud-extensions-ext-appconfig-add-to-profile.md#cloud-extensions-ext-appconfig-add-to-profile-adding-the-extension-to-a-profile).
+ Set the authentication of the profile to `none`, because the function sends no credentials. For the steps, see [Turning authentication off](cloud-extensions-security.md#cloud-extensions-security-turning-authentication-off).
+ Make sure that the IAM execution role of the extension allows `appconfig:StartConfigurationSession` and `appconfig:GetLatestConfiguration` on the configurations that the function reads. For the policy, see [Required IAM permissions](cloud-extensions-ext-appconfig-prerequisites.md#cloud-extensions-ext-appconfig-prerequisites-required-iam-permissions).

The function itself needs no AWS AppConfig permissions. The extension calls AWS AppConfig with the execution role of the extension. The role of the function needs the permissions to write logs, which the `AWSLambdaBasicExecutionRole` managed policy provides. The role also needs the `cloudextensions:SyncState` action on all resources, which the runtime uses to retrieve the profile. For the action, see [Permissions for the runtime](cloud-extensions-security.md#cloud-extensions-security-permissions-for-the-runtime). The CloudFormation template in this example grants both.

The function sends no credentials to the extension, like the curl examples. The example works only when the authentication of the profile is `none`. To sign requests, see [Authentication](cloud-extensions-security.md#cloud-extensions-security-authentication).

**Write the function**

Save the following code as `lambda_function.py`:

```python
import base64
import json
import urllib.error
import urllib.request
ENDPOINT = "http://localhost:5333/appconfig/"
# The names of the AWS AppConfig resources that the CloudFormation template creates.
APPLICATION = "appconfig-extension-lambda-demo"
ENVIRONMENT = "demo"
def call(operation, params):
    """Send a request to the extension and return the parsed JSON response."""
    request = urllib.request.Request(
        ENDPOINT,
        data=json.dumps(params).encode(),
        method="POST",
        headers={
            "X-Amz-Target": "AppConfig." + operation,
            "Content-Type": "application/x-amz-json-1.1",
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=10) as response:
            return json.loads(response.read())
    except urllib.error.HTTPError as error:
        # The X-Amzn-Errortype header holds the name of the error, such as ValidationException.
        raise RuntimeError(
            f"{error.code} {error.headers.get('X-Amzn-Errortype')}: {error.read().decode()}"
        ) from error
def lambda_handler(event, context):
    # GetConfiguration: the whole configuration. The content is base64-encoded.
    settings = call("GetConfiguration", {
        "application": APPLICATION,
        "environment": ENVIRONMENT,
        "configuration": "service-settings",
    })
    config = json.loads(base64.b64decode(settings["content"]))
    # GetFlag: one feature flag, with its enabled state and its attributes
    flag = call("GetFlag", {
        "application": APPLICATION,
        "environment": ENVIRONMENT,
        "configuration": "simple-flags",
        "flag": "banner",
    })
    return {
        "greeting": config["greeting"],
        "revision": settings["revision"],
        "bannerEnabled": flag["enabled"],
        "bannerMessage": flag.get("attributes", {}).get("message", {}).get("string"),
    }
```

The code works as follows:
+ `call` sends a `POST` request to the extension with `urllib`, with the operation in the `X-Amz-Target` header and the parameters as a JSON body.
+ When the extension returns an error, `call` raises a `RuntimeError` with the HTTP status, the error name from the `X-Amzn-Errortype` header, and the body.
+ The handler reads the configuration `service-settings` with `GetConfiguration`, and decodes its base64 content. The handler reads the flag `banner` of the configuration `simple-flags` with `GetFlag`.

**Create the function and its data with AWS CloudFormation**

The following template creates the AWS AppConfig data that the function reads and the function with the runtime layer. The template also creates the IAM role of the function, which includes the permission to retrieve the profile. The template also creates a managed policy with the permissions that the extension needs. The data has an application named `appconfig-extension-lambda-demo` and an environment named `demo`. The data also has a freeform configuration profile named `service-settings`, a feature flag profile named `simple-flags`, and a deployment strategy that deploys at once. The `ExtensionLayerArn` parameter reads the public parameter that holds the ARN of the Lambda extension, so a stack update picks up the latest ARN. The `ProfileName` parameter sets the `AWS_CLOUDEXTENSIONS_PROFILE` environment variable of the function. The template uses the x86\_64 architecture. For arm64, set `Architectures` to `arm64` and use the `arm64` public parameter.

Save the following template as `template.yaml`, and put `lambda_function.py` in a folder named `function` next to it:

```yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda function that reads configuration through the Cloud Extensions AWS AppConfig extension
Parameters:
  ExtensionLayerArn:
    Type: AWS::SSM::Parameter::Value<String>
    Default: /aws/service/aws-cloudextensions/lambda-extension/amd64/latest
    Description: Public parameter that holds the ARN of the Cloud Extensions Lambda extension for x86_64
  ProfileName:
    Type: String
    Default: my-application
    Description: Name or ID of the Cloud Extensions profile that the runtime loads
Resources:
  DemoApplication:
    Type: AWS::AppConfig::Application
    Properties:
      Name: appconfig-extension-lambda-demo
  DemoEnvironment:
    Type: AWS::AppConfig::Environment
    Properties:
      ApplicationId: !Ref DemoApplication
      Name: demo
  InstantStrategy:
    Type: AWS::AppConfig::DeploymentStrategy
    Properties:
      Name: appconfig-extension-lambda-demo-instant
      DeploymentDurationInMinutes: 0
      FinalBakeTimeInMinutes: 0
      GrowthFactor: 100
      ReplicateTo: NONE
  SettingsProfile:
    Type: AWS::AppConfig::ConfigurationProfile
    Properties:
      ApplicationId: !Ref DemoApplication
      Name: service-settings
      LocationUri: hosted
  SettingsVersion:
    Type: AWS::AppConfig::HostedConfigurationVersion
    Properties:
      ApplicationId: !Ref DemoApplication
      ConfigurationProfileId: !Ref SettingsProfile
      ContentType: application/json
      Content: '{"greeting":"hello from the Lambda demo","maxItems":10}'
  SettingsDeployment:
    Type: AWS::AppConfig::Deployment
    Properties:
      ApplicationId: !Ref DemoApplication
      EnvironmentId: !Ref DemoEnvironment
      DeploymentStrategyId: !Ref InstantStrategy
      ConfigurationProfileId: !Ref SettingsProfile
      ConfigurationVersion: !GetAtt SettingsVersion.VersionNumber
  FlagsProfile:
    Type: AWS::AppConfig::ConfigurationProfile
    Properties:
      ApplicationId: !Ref DemoApplication
      Name: simple-flags
      LocationUri: hosted
      Type: AWS.AppConfig.FeatureFlags
  FlagsVersion:
    Type: AWS::AppConfig::HostedConfigurationVersion
    Properties:
      ApplicationId: !Ref DemoApplication
      ConfigurationProfileId: !Ref FlagsProfile
      ContentType: application/json
      Content: |
        {
          "version": "1",
          "flags": {
            "banner": {
              "name": "banner",
              "attributes": {
                "message": { "constraints": { "type": "string", "required": true } }
              }
            }
          },
          "values": {
            "banner": { "enabled": true, "message": "Welcome to the demo" }
          }
        }
  FlagsDeployment:
    Type: AWS::AppConfig::Deployment
    DependsOn: SettingsDeployment
    Properties:
      ApplicationId: !Ref DemoApplication
      EnvironmentId: !Ref DemoEnvironment
      DeploymentStrategyId: !Ref InstantStrategy
      ConfigurationProfileId: !Ref FlagsProfile
      ConfigurationVersion: !GetAtt FlagsVersion.VersionNumber
  FunctionRole:
    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
      Policies:
        - PolicyName: SyncProfileState
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: cloudextensions:SyncState
                Resource: '*'
  ExtensionPermissionsPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      Description: Permissions for the IAM execution role of the AWS AppConfig extension
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - appconfig:StartConfigurationSession
              - appconfig:GetLatestConfiguration
            Resource: !Sub arn:${AWS::Partition}:appconfig:${AWS::Region}:${AWS::AccountId}:application/${DemoApplication}/environment/${DemoEnvironment}/configuration/*
  DemoFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: appconfig-extension-demo
      Runtime: python3.12
      Architectures:
        - x86_64
      Handler: lambda_function.lambda_handler
      Role: !GetAtt FunctionRole.Arn
      Timeout: 30
      Layers:
        - !Ref ExtensionLayerArn
      Environment:
        Variables:
          AWS_CLOUDEXTENSIONS_PROFILE: !Ref ProfileName
      Code: function/
Outputs:
  FunctionName:
    Value: !Ref DemoFunction
  ExtensionPermissionsPolicyArn:
    Description: Attach this policy to the IAM execution role of the extension
    Value: !Ref ExtensionPermissionsPolicy
```

The `Code` property points to a local folder. To upload the folder and deploy the stack, run the following commands. Replace `amzn-s3-demo-bucket` with the name of an Amazon S3 bucket in `us-west-2` that you own:

```bash
aws cloudformation package \
  --region us-west-2 \
  --template-file template.yaml \
  --s3-bucket amzn-s3-demo-bucket \
  --output-template-file packaged.yaml
aws cloudformation deploy \
  --region us-west-2 \
  --template-file packaged.yaml \
  --stack-name appconfig-extension-lambda-demo \
  --capabilities CAPABILITY_IAM
```

The stack outputs the ARN of the managed policy. Attach the policy to the IAM execution role of the extension. This template doesn't create that role, because the role needs a trust policy. The trust policy allows the role that the runtime runs as to assume the role. For the trust policy, see [IAM execution role](cloud-extensions-security.md#cloud-extensions-security-iam-execution-role). The template also doesn't create the profile or the profile entry. To create the profile, see [Step 2: Creating a profile](cloud-extensions-getting-started.md#cloud-extensions-getting-started-step-2-creating-a-profile). To create the profile entry, see [Adding the extension with the AWS CLI](cloud-extensions-ext-appconfig-add-to-profile.md#cloud-extensions-ext-appconfig-add-to-profile-adding-the-extension-with-the-aws-cli).

**Invoke the function**

To run the function, run the following command:

```bash
aws lambda invoke \
  --region us-west-2 \
  --function-name appconfig-extension-demo \
  --cli-binary-format raw-in-base64-out \
  --payload '{}' \
  response.json
cat response.json | jq
```

The output looks like the following. The value of `revision` depends on the content of the configuration.

```json
{
  "greeting": "hello from the Lambda demo",
  "revision": "{{revision}}",
  "bannerEnabled": true,
  "bannerMessage": "Welcome to the demo"
}
```

The first request for a configuration waits for the extension to retrieve the configuration from AWS AppConfig. To retrieve the configurations when the extension starts, add them to the **Prefetch list**.

If the runtime isn't running in the function, the invocation fails with a `URLError` and the message `Connection refused`. Check that you attached the layer and that the runtime started.

**Clean up**

To delete the function, the AWS AppConfig data, and the managed policy, run the following command:

```bash
aws cloudformation delete-stack --region us-west-2 --stack-name appconfig-extension-lambda-demo
```

Detach the managed policy from the IAM execution role of the extension before you delete the stack. Otherwise, the deletion of the policy fails.

AWS AppConfig blocks the deletion of an environment or a configuration profile that received a configuration request in the last 60 minutes. The extension sends the requests when your function reads the configurations. If the deletion of the stack fails for this reason, wait 60 minutes, and run the command again.