Skip to content

Commit

Permalink
Add AppConfig feature flags example (#928)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
calavera authored Sep 23, 2024
1 parent 8572af6 commit c3575f6
Show file tree
Hide file tree
Showing 16 changed files with 8,164 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ output.json
.aws-sam
build
.vscode

node_modules
cdk.out
1 change: 1 addition & 0 deletions examples/advanced-appconfig-feature-flags/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target
24 changes: 24 additions & 0 deletions examples/advanced-appconfig-feature-flags/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "lambda-appconfig"
version = "0.1.0"
edition = "2021"

# Starting in Rust 1.62 you can use `cargo add` to add dependencies
# to your project.
#
# If you're using an older Rust version,
# download cargo-edit(https://github.com/killercup/cargo-edit#installation)
# to install the `add` subcommand.
#
# Running `cargo add DEPENDENCY_NAME` will
# add the latest version of a dependency to the list,
# and it will keep the alphabetic ordering for you.

[dependencies]
async-trait = "0.1.68"
lambda_runtime = "0.13"
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "1.0"
tokio = { version = "1", features = ["macros"] }
65 changes: 65 additions & 0 deletions examples/advanced-appconfig-feature-flags/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Rust Lambda with AppConfig Feature Flag

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.

## Lambda Function (src/main.rs)

The Lambda function is written in Rust and does the following:

1. Integrates with AWS AppConfig to fetch configuration at runtime.
2. Uses a feature flag to determine whether to respond in Spanish.
3. Processes incoming events.
4. Returns a response based on the event and the current feature flag state.

The function is designed to work with the AWS AppConfig Extension for Lambda, allowing for efficient configuration retrieval.

## Deployment (cdk directory)

The project uses AWS CDK for infrastructure as code and deployment. To deploy the project:

1. Ensure you have the AWS CDK CLI installed and configured.
2. Navigate to the `cdk` directory.
3. Install dependencies:
```
npm install
```
4. Build the CDK stack:
```
npm run build
```
5. Deploy the stack:
```
cdk deploy
```

## AWS Resources (cdk/lib/cdk-stack.ts)

The CDK stack creates the following AWS resources:

1. **AppConfig Application**: Named "MyRustLambdaApp", this is the container for your configuration and feature flags.

2. **AppConfig Environment**: A "Production" environment is created within the application.

3. **AppConfig Configuration Profile**: Defines the schema and validation for your configuration.

4. **AppConfig Hosted Configuration Version**: Contains the actual configuration data, including the "spanish-response" feature flag.

5. **AppConfig Deployment Strategy**: Defines how configuration changes are rolled out.

6. **Lambda Function**: A Rust-based function that uses the AppConfig configuration.
- Uses the AWS AppConfig Extension Layer for efficient configuration retrieval.
- Configured with ARM64 architecture and 128MB of memory.
- 30-second timeout.

7. **CloudWatch Alarm**: Monitors the Lambda function's error rate.
- Triggers if there are more than 5 errors per minute.

8. **AppConfig Deployment**: Connects all AppConfig components and includes a rollback trigger based on the CloudWatch alarm.

9. **IAM Role**: Grants the Lambda function permissions to interact with AppConfig and CloudWatch.

This setup allows for feature flagging with automatic rollback capabilities, ensuring rapid and safe deployment of new features or configurations.

## Usage

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.
6 changes: 6 additions & 0 deletions examples/advanced-appconfig-feature-flags/cdk/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.ts
!*.d.ts

# CDK asset staging directory
.cdk.staging
cdk.out
14 changes: 14 additions & 0 deletions examples/advanced-appconfig-feature-flags/cdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Welcome to your CDK TypeScript project

This is a blank project for CDK development with TypeScript.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

## Useful commands

* `npm run build` compile typescript to js
* `npm run watch` watch for changes and compile
* `npm run test` perform the jest unit tests
* `npx cdk deploy` deploy this stack to your default AWS account/region
* `npx cdk diff` compare deployed stack with current state
* `npx cdk synth` emits the synthesized CloudFormation template
21 changes: 21 additions & 0 deletions examples/advanced-appconfig-feature-flags/cdk/bin/cdk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { CdkStack } from '../lib/cdk-stack';

const app = new cdk.App();
new CdkStack(app, 'CdkStack', {
/* If you don't specify 'env', this stack will be environment-agnostic.
* Account/Region-dependent features and context lookups will not work,
* but a single synthesized template can be deployed anywhere. */

/* Uncomment the next line to specialize this stack for the AWS Account
* and Region that are implied by the current CLI configuration. */
// env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },

/* Uncomment the next line if you know exactly what Account and Region you
* want to deploy the stack to. */
// env: { account: '123456789012', region: 'us-east-1' },

/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
});
72 changes: 72 additions & 0 deletions examples/advanced-appconfig-feature-flags/cdk/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"app": "npx ts-node --prefer-ts-exts bin/cdk.ts",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"**/*.d.ts",
"**/*.js",
"tsconfig.json",
"package*.json",
"yarn.lock",
"node_modules",
"test"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false
}
}
8 changes: 8 additions & 0 deletions examples/advanced-appconfig-feature-flags/cdk/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
}
};
110 changes: 110 additions & 0 deletions examples/advanced-appconfig-feature-flags/cdk/lib/cdk-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import * as cdk from 'aws-cdk-lib';
import * as appconfig from 'aws-cdk-lib/aws-appconfig';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
import { Construct } from 'constructs';
import { RustFunction } from 'cargo-lambda-cdk';

export class CdkStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// Create AppConfig Application
const application = new appconfig.CfnApplication(this, 'MyApplication', {
name: 'MyRustLambdaApp',
});

// Create AppConfig Environment
const environment = new appconfig.CfnEnvironment(this, 'MyEnvironment', {
applicationId: application.ref,
name: 'Production',
});

// Create AppConfig Configuration Profile
const configProfile = new appconfig.CfnConfigurationProfile(this, 'MyConfigProfile', {
applicationId: application.ref,
name: 'MyConfigProfile',
locationUri: 'hosted',
});

// Create AppConfig Hosted Configuration Version
const hostedConfig = new appconfig.CfnHostedConfigurationVersion(this, 'MyHostedConfig', {
applicationId: application.ref,
configurationProfileId: configProfile.ref,
content: JSON.stringify({
'spanish-response': false
}),
contentType: 'application/json',
});

// Create AppConfig Deployment Strategy
const deploymentStrategy = new appconfig.CfnDeploymentStrategy(this, 'MyDeploymentStrategy', {
name: 'MyDeploymentStrategy',
deploymentDurationInMinutes: 0,
growthFactor: 100,
replicateTo: 'NONE',
});

const architecture = lambda.Architecture.ARM_64;
const layerVersion = architecture === lambda.Architecture.ARM_64 ? '68' : '60';

// Create Lambda function using cargo-lambda-cdk
const myFunction = new RustFunction(this, 'MyRustFunction', {
functionName: 'my-rust-lambda',
manifestPath: '..', // Points to the parent directory where Cargo.toml is located
architecture,
memorySize: 128,
timeout: cdk.Duration.seconds(30),
environment: {
APPLICATION_ID: application.ref,
ENVIRONMENT_ID: environment.ref,
CONFIGURATION_PROFILE_ID: configProfile.ref,
AWS_APPCONFIG_EXTENSION_PREFETCH_LIST: `/applications/${application.ref}/environments/${environment.ref}/configurations/${configProfile.ref}`,
},
layers: [
lambda.LayerVersion.fromLayerVersionArn(
this,
'AppConfigExtensionLayer',
`arn:aws:lambda:${this.region}:027255383542:layer:AWS-AppConfig-Extension:${layerVersion}`
),
],
});

// Create CloudWatch Alarm for rollback
const errorRateAlarm = new cloudwatch.Alarm(this, 'ErrorRateAlarm', {
metric: myFunction.metricErrors({
period: cdk.Duration.minutes(1),
statistic: 'sum',
}),
threshold: 5,
evaluationPeriods: 1,
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
alarmDescription: 'Alarm if the error rate is greater than 5 errors per minute',
});

// Create AppConfig Deployment with rollback configuration
new appconfig.CfnDeployment(this, 'MyDeployment', {
applicationId: application.ref,
environmentId: environment.ref,
deploymentStrategyId: deploymentStrategy.ref,
configurationProfileId: configProfile.ref,
configurationVersion: hostedConfig.ref,
tags: [
{
key: 'RollbackTrigger',
value: errorRateAlarm.alarmArn,
},
],
});

// Grant AppConfig permissions to the Lambda function
myFunction.addToRolePolicy(new cdk.aws_iam.PolicyStatement({
actions: [
'appconfig:GetConfiguration',
'appconfig:StartConfigurationSession',
'cloudwatch:PutMetricData',
],
resources: ['*'],
}));
}
}
Loading

0 comments on commit c3575f6

Please sign in to comment.