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. 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_PROFILEenvironment 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 theappconfigdatacapability. For the steps, see 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. -
Make sure that the IAM execution role of the extension allows
appconfig:StartConfigurationSessionandappconfig:GetLatestConfigurationon the configurations that the function reads. For the policy, see 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. 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.
Write the function
Save the following code as lambda_function.py:
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:
-
callsends aPOSTrequest to the extension withurllib, with the operation in theX-Amz-Targetheader and the parameters as a JSON body. -
When the extension returns an error,
callraises aRuntimeErrorwith the HTTP status, the error name from theX-Amzn-Errortypeheader, and the body. -
The handler reads the configuration
service-settingswithGetConfiguration, and decodes its base64 content. The handler reads the flagbannerof the configurationsimple-flagswithGetFlag.
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:
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:
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. The template also doesn't create the profile or the profile entry. To create the profile, see Step 2: Creating a profile. To create the profile entry, see Adding the extension with the AWS CLI.
Invoke the function
To run the function, run the following command:
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.
{ "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:
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.