Skip to content

Commit c3575f6

Browse files
authored
Add AppConfig feature flags example (#928)
This example shows how to integrate AppConfig with Rust Lambda functions. It includes CDK constructs to deploy the basic AppConfig scaffolding, and the AppConfig Lambda extension to reduce the latency fetching the AppConfig configuration.
1 parent 8572af6 commit c3575f6

File tree

16 files changed

+8164
-0
lines changed

16 files changed

+8164
-0
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,6 @@ output.json
1313
.aws-sam
1414
build
1515
.vscode
16+
17+
node_modules
18+
cdk.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/target
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
[package]
2+
name = "lambda-appconfig"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# Starting in Rust 1.62 you can use `cargo add` to add dependencies
7+
# to your project.
8+
#
9+
# If you're using an older Rust version,
10+
# download cargo-edit(https://github.com/killercup/cargo-edit#installation)
11+
# to install the `add` subcommand.
12+
#
13+
# Running `cargo add DEPENDENCY_NAME` will
14+
# add the latest version of a dependency to the list,
15+
# and it will keep the alphabetic ordering for you.
16+
17+
[dependencies]
18+
async-trait = "0.1.68"
19+
lambda_runtime = "0.13"
20+
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
21+
serde = { version = "1.0", features = ["derive"] }
22+
serde_json = "1.0"
23+
thiserror = "1.0"
24+
tokio = { version = "1", features = ["macros"] }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Rust Lambda with AppConfig Feature Flag
2+
3+
This project demonstrates a Rust-based AWS Lambda function that uses AWS AppConfig for feature flagging. The function is deployed using AWS CDK and includes automatic rollback capabilities based on error rates.
4+
5+
## Lambda Function (src/main.rs)
6+
7+
The Lambda function is written in Rust and does the following:
8+
9+
1. Integrates with AWS AppConfig to fetch configuration at runtime.
10+
2. Uses a feature flag to determine whether to respond in Spanish.
11+
3. Processes incoming events.
12+
4. Returns a response based on the event and the current feature flag state.
13+
14+
The function is designed to work with the AWS AppConfig Extension for Lambda, allowing for efficient configuration retrieval.
15+
16+
## Deployment (cdk directory)
17+
18+
The project uses AWS CDK for infrastructure as code and deployment. To deploy the project:
19+
20+
1. Ensure you have the AWS CDK CLI installed and configured.
21+
2. Navigate to the `cdk` directory.
22+
3. Install dependencies:
23+
```
24+
npm install
25+
```
26+
4. Build the CDK stack:
27+
```
28+
npm run build
29+
```
30+
5. Deploy the stack:
31+
```
32+
cdk deploy
33+
```
34+
35+
## AWS Resources (cdk/lib/cdk-stack.ts)
36+
37+
The CDK stack creates the following AWS resources:
38+
39+
1. **AppConfig Application**: Named "MyRustLambdaApp", this is the container for your configuration and feature flags.
40+
41+
2. **AppConfig Environment**: A "Production" environment is created within the application.
42+
43+
3. **AppConfig Configuration Profile**: Defines the schema and validation for your configuration.
44+
45+
4. **AppConfig Hosted Configuration Version**: Contains the actual configuration data, including the "spanish-response" feature flag.
46+
47+
5. **AppConfig Deployment Strategy**: Defines how configuration changes are rolled out.
48+
49+
6. **Lambda Function**: A Rust-based function that uses the AppConfig configuration.
50+
- Uses the AWS AppConfig Extension Layer for efficient configuration retrieval.
51+
- Configured with ARM64 architecture and 128MB of memory.
52+
- 30-second timeout.
53+
54+
7. **CloudWatch Alarm**: Monitors the Lambda function's error rate.
55+
- Triggers if there are more than 5 errors per minute.
56+
57+
8. **AppConfig Deployment**: Connects all AppConfig components and includes a rollback trigger based on the CloudWatch alarm.
58+
59+
9. **IAM Role**: Grants the Lambda function permissions to interact with AppConfig and CloudWatch.
60+
61+
This setup allows for feature flagging with automatic rollback capabilities, ensuring rapid and safe deployment of new features or configurations.
62+
63+
## Usage
64+
65+
After deployment, you can update the feature flag in AppConfig to control the Lambda function's behavior. The function will automatically fetch the latest configuration, and if error rates exceed the threshold, AppConfig will automatically roll back to the previous stable configuration.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
*.ts
2+
!*.d.ts
3+
4+
# CDK asset staging directory
5+
.cdk.staging
6+
cdk.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Welcome to your CDK TypeScript project
2+
3+
This is a blank project for CDK development with TypeScript.
4+
5+
The `cdk.json` file tells the CDK Toolkit how to execute your app.
6+
7+
## Useful commands
8+
9+
* `npm run build` compile typescript to js
10+
* `npm run watch` watch for changes and compile
11+
* `npm run test` perform the jest unit tests
12+
* `npx cdk deploy` deploy this stack to your default AWS account/region
13+
* `npx cdk diff` compare deployed stack with current state
14+
* `npx cdk synth` emits the synthesized CloudFormation template
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/env node
2+
import 'source-map-support/register';
3+
import * as cdk from 'aws-cdk-lib';
4+
import { CdkStack } from '../lib/cdk-stack';
5+
6+
const app = new cdk.App();
7+
new CdkStack(app, 'CdkStack', {
8+
/* If you don't specify 'env', this stack will be environment-agnostic.
9+
* Account/Region-dependent features and context lookups will not work,
10+
* but a single synthesized template can be deployed anywhere. */
11+
12+
/* Uncomment the next line to specialize this stack for the AWS Account
13+
* and Region that are implied by the current CLI configuration. */
14+
// env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
15+
16+
/* Uncomment the next line if you know exactly what Account and Region you
17+
* want to deploy the stack to. */
18+
// env: { account: '123456789012', region: 'us-east-1' },
19+
20+
/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
21+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
{
2+
"app": "npx ts-node --prefer-ts-exts bin/cdk.ts",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"**/*.d.ts",
11+
"**/*.js",
12+
"tsconfig.json",
13+
"package*.json",
14+
"yarn.lock",
15+
"node_modules",
16+
"test"
17+
]
18+
},
19+
"context": {
20+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
21+
"@aws-cdk/core:checkSecretUsage": true,
22+
"@aws-cdk/core:target-partitions": [
23+
"aws",
24+
"aws-cn"
25+
],
26+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
27+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
28+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
29+
"@aws-cdk/aws-iam:minimizePolicies": true,
30+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
31+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
32+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
33+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
34+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
35+
"@aws-cdk/core:enablePartitionLiterals": true,
36+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
37+
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
38+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
39+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
40+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
41+
"@aws-cdk/aws-route53-patters:useCertificate": true,
42+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
43+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
44+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
45+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
46+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
47+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
48+
"@aws-cdk/aws-redshift:columnId": true,
49+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
50+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
51+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
52+
"@aws-cdk/aws-kms:aliasNameRef": true,
53+
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
54+
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
55+
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
56+
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
57+
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
58+
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
59+
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
60+
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
61+
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
62+
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
63+
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
64+
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
65+
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
66+
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
67+
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
68+
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
69+
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
70+
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false
71+
}
72+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = {
2+
testEnvironment: 'node',
3+
roots: ['<rootDir>/test'],
4+
testMatch: ['**/*.test.ts'],
5+
transform: {
6+
'^.+\\.tsx?$': 'ts-jest'
7+
}
8+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import * as cdk from 'aws-cdk-lib';
2+
import * as appconfig from 'aws-cdk-lib/aws-appconfig';
3+
import * as lambda from 'aws-cdk-lib/aws-lambda';
4+
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
5+
import { Construct } from 'constructs';
6+
import { RustFunction } from 'cargo-lambda-cdk';
7+
8+
export class CdkStack extends cdk.Stack {
9+
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
10+
super(scope, id, props);
11+
12+
// Create AppConfig Application
13+
const application = new appconfig.CfnApplication(this, 'MyApplication', {
14+
name: 'MyRustLambdaApp',
15+
});
16+
17+
// Create AppConfig Environment
18+
const environment = new appconfig.CfnEnvironment(this, 'MyEnvironment', {
19+
applicationId: application.ref,
20+
name: 'Production',
21+
});
22+
23+
// Create AppConfig Configuration Profile
24+
const configProfile = new appconfig.CfnConfigurationProfile(this, 'MyConfigProfile', {
25+
applicationId: application.ref,
26+
name: 'MyConfigProfile',
27+
locationUri: 'hosted',
28+
});
29+
30+
// Create AppConfig Hosted Configuration Version
31+
const hostedConfig = new appconfig.CfnHostedConfigurationVersion(this, 'MyHostedConfig', {
32+
applicationId: application.ref,
33+
configurationProfileId: configProfile.ref,
34+
content: JSON.stringify({
35+
'spanish-response': false
36+
}),
37+
contentType: 'application/json',
38+
});
39+
40+
// Create AppConfig Deployment Strategy
41+
const deploymentStrategy = new appconfig.CfnDeploymentStrategy(this, 'MyDeploymentStrategy', {
42+
name: 'MyDeploymentStrategy',
43+
deploymentDurationInMinutes: 0,
44+
growthFactor: 100,
45+
replicateTo: 'NONE',
46+
});
47+
48+
const architecture = lambda.Architecture.ARM_64;
49+
const layerVersion = architecture === lambda.Architecture.ARM_64 ? '68' : '60';
50+
51+
// Create Lambda function using cargo-lambda-cdk
52+
const myFunction = new RustFunction(this, 'MyRustFunction', {
53+
functionName: 'my-rust-lambda',
54+
manifestPath: '..', // Points to the parent directory where Cargo.toml is located
55+
architecture,
56+
memorySize: 128,
57+
timeout: cdk.Duration.seconds(30),
58+
environment: {
59+
APPLICATION_ID: application.ref,
60+
ENVIRONMENT_ID: environment.ref,
61+
CONFIGURATION_PROFILE_ID: configProfile.ref,
62+
AWS_APPCONFIG_EXTENSION_PREFETCH_LIST: `/applications/${application.ref}/environments/${environment.ref}/configurations/${configProfile.ref}`,
63+
},
64+
layers: [
65+
lambda.LayerVersion.fromLayerVersionArn(
66+
this,
67+
'AppConfigExtensionLayer',
68+
`arn:aws:lambda:${this.region}:027255383542:layer:AWS-AppConfig-Extension:${layerVersion}`
69+
),
70+
],
71+
});
72+
73+
// Create CloudWatch Alarm for rollback
74+
const errorRateAlarm = new cloudwatch.Alarm(this, 'ErrorRateAlarm', {
75+
metric: myFunction.metricErrors({
76+
period: cdk.Duration.minutes(1),
77+
statistic: 'sum',
78+
}),
79+
threshold: 5,
80+
evaluationPeriods: 1,
81+
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
82+
alarmDescription: 'Alarm if the error rate is greater than 5 errors per minute',
83+
});
84+
85+
// Create AppConfig Deployment with rollback configuration
86+
new appconfig.CfnDeployment(this, 'MyDeployment', {
87+
applicationId: application.ref,
88+
environmentId: environment.ref,
89+
deploymentStrategyId: deploymentStrategy.ref,
90+
configurationProfileId: configProfile.ref,
91+
configurationVersion: hostedConfig.ref,
92+
tags: [
93+
{
94+
key: 'RollbackTrigger',
95+
value: errorRateAlarm.alarmArn,
96+
},
97+
],
98+
});
99+
100+
// Grant AppConfig permissions to the Lambda function
101+
myFunction.addToRolePolicy(new cdk.aws_iam.PolicyStatement({
102+
actions: [
103+
'appconfig:GetConfiguration',
104+
'appconfig:StartConfigurationSession',
105+
'cloudwatch:PutMetricData',
106+
],
107+
resources: ['*'],
108+
}));
109+
}
110+
}

0 commit comments

Comments
 (0)