You need to enable JavaScript to run this app. 求AWS CDK/TypeScript编写的供Lambda使用的AppConfig资源部署示例
优惠活动
大模型
产品
解决方案
定价
更多

求AWS CDK/TypeScript编写的供Lambda使用的AppConfig资源部署示例

AWS CDK/TypeScript 部署AppConfig + Lambda 调用完整示例

前置依赖

  • 已安装AWS CDK CLI并完成CDK环境引导
  • 项目需安装以下依赖包:aws-cdk-lib constructs @aws-sdk/client-appconfigdata(Lambda运行时依赖)

CDK栈完整实现(TypeScript)

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 iam from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';

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

    // 1. 创建AppConfig顶层应用
    const appConfigApp = new appconfig.CfnApplication(this, 'DemoApp', {
      name: 'demo-app',
      description: '示例AppConfig应用'
    });

    // 2. 创建AppConfig环境(可按需求创建dev/test/prod多套环境)
    const appConfigEnv = new appconfig.CfnEnvironment(this, 'DemoEnv', {
      applicationId: appConfigApp.ref,
      name: 'dev',
      description: '开发环境'
    });

    // 3. 创建配置剖面
    const configProfile = new appconfig.CfnConfigurationProfile(this, 'DemoConfigProfile', {
      applicationId: appConfigApp.ref,
      name: 'demo-runtime-config',
      locationUri: 'hosted', // 配置内容托管在AppConfig侧
      type: 'AWS.Freeform', // 自由格式配置,也可选择特性标志格式
    });

    // 4. 上传具体配置内容(JSON格式示例)
    const configVersion = new appconfig.CfnHostedConfigurationVersion(this, 'DemoConfigVersion', {
      applicationId: appConfigApp.ref,
      configurationProfileId: configProfile.ref,
      content: JSON.stringify({
        featureToggleA: true,
        maxRetryCount: 3,
        apiEndpoint: 'https://api.example.com/v1'
      }),
      contentType: 'application/json'
    });

    // 5. 定义部署策略(此处用立即部署策略,可按需求配置灰度/增量部署)
    const deploymentStrategy = new appconfig.CfnDeploymentStrategy(this, 'DemoDeploymentStrategy', {
      name: 'immediate-deploy',
      deploymentDurationInMinutes: 0,
      growthFactor: 100,
      replicateTo: 'NONE',
      finalBakeTimeInMinutes: 0
    });

    // 6. 将配置部署到对应环境
    new appconfig.CfnDeployment(this, 'DemoConfigDeployment', {
      applicationId: appConfigApp.ref,
      environmentId: appConfigEnv.ref,
      configurationProfileId: configProfile.ref,
      configurationVersion: configVersion.ref,
      deploymentStrategyId: deploymentStrategy.ref
    });

    // 7. 创建调用AppConfig的Lambda函数
    const appConfigDemoLambda = new lambda.Function(this, 'AppConfigDemoLambda', {
      runtime: lambda.Runtime.NODEJS_18_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('lambda'), // Lambda代码存放在项目根目录lambda文件夹下
      environment: {
        APPCONFIG_APP_ID: appConfigApp.ref,
        APPCONFIG_ENV_ID: appConfigEnv.ref,
        APPCONFIG_PROFILE_ID: configProfile.ref
      }
    });

    // 8. 给Lambda授予调用AppConfig拉取配置的权限
    appConfigDemoLambda.addToRolePolicy(new iam.PolicyStatement({
      effect: iam.Effect.ALLOW,
      actions: [
        'appconfig:StartConfigurationSession',
        'appconfig:GetLatestConfiguration'
      ],
      resources: [
        `arn:aws:appconfig:${this.region}:${this.account}:application/${appConfigApp.ref}/environment/${appConfigEnv.ref}/configuration/${configProfile.ref}`
      ]
    }));
  }
}

Lambda 侧调用AppConfig配置示例代码

存放在lambda/index.ts路径下:

import { AppConfigDataClient, StartConfigurationSessionCommand, GetLatestConfigurationCommand } from "@aws-sdk/client-appconfigdata";

const appConfigClient = new AppConfigDataClient({});
const appConfigParams = {
  ApplicationIdentifier: process.env.APPCONFIG_APP_ID!,
  EnvironmentIdentifier: process.env.APPCONFIG_ENV_ID!,
  ConfigurationProfileIdentifier: process.env.APPCONFIG_PROFILE_ID!,
};
// 可缓存会话token减少请求次数,token有效期为24小时
let cachedConfigToken: string | undefined;

export const handler = async () => {
  // 首次调用或token过期时启动新配置会话
  if (!cachedConfigToken) {
    const sessionResp = await appConfigClient.send(new StartConfigurationSessionCommand(appConfigParams));
    cachedConfigToken = sessionResp.InitialConfigurationToken;
  }

  // 拉取最新配置
  const configResp = await appConfigClient.send(new GetLatestConfigurationCommand({
    ConfigurationToken: cachedConfigToken!
  }));
  // 更新下次请求用的token
  cachedConfigToken = configResp.NextPollConfigurationToken;

  // 将Uint8Array格式的配置内容转为JSON
  const configContent = Buffer.from(configResp.Configuration!).toString('utf8');
  const runtimeConfig = JSON.parse(configContent);

  // 业务逻辑使用配置
  console.log('拉取到的AppConfig配置:', runtimeConfig);
  
  return {
    statusCode: 200,
    body: JSON.stringify(runtimeConfig)
  };
};

部署与验证步骤

  • 执行cdk deploy部署所有资源
  • 到AWS控制台触发Lambda测试,可在CloudWatch日志中查看拉取到的AppConfig配置内容
  • 后续修改AppConfig配置后无需重新部署Lambda,配置会按设置的部署策略自动生效

内容的提问来源于stack exchange,提问作者Maxim Suponya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 01:06:00