如何在AWS AppConfig启动配置会话时动态获取标识符?
解决AWS AppConfig标识符硬编码的动态获取方案
方案1:环境变量注入(最推荐)
直接把基础设施生成的AppConfig标识符通过环境变量注入应用,代码读取环境变量而非硬编码,这是最简单且符合DevOps最佳实践的方式。
修改config.ts
// Used for appConfig export const APP_CONFIG_APP_NAME = process.env.APP_CONFIG_APP_NAME || 'tableName'; export const APP_CONFIG_APP_IDENTIFIER = process.env.APP_CONFIG_APP_IDENTIFIER || ''; export const APP_CONFIG_ENV_IDENTIFIER = process.env.APP_CONFIG_ENV_IDENTIFIER || ''; export const APP_CONFIG_PROFILE_IDENTIFIER = process.env.APP_CONFIG_PROFILE_IDENTIFIER || ''; export const APP_REGION = process.env.APP_REGION || 'us-east-1';
部署时注入环境变量
通过基础设施即代码(CloudFormation/CDK/Terraform)将生成的AppConfig标识符传递给应用:
- CloudFormation:在资源的
Environment属性中添加变量 - CDK:使用
addEnvironment方法为服务注入变量 - Terraform:在部署资源的
environment块中配置变量
方案2:通过AWS AppConfig SDK动态查询标识符
如果无法提前注入环境变量,可以使用AWS AppConfig主SDK,通过应用/环境/配置文件的名称查询对应的ID。
步骤1:安装AppConfig SDK
npm install @aws-sdk/client-appconfig
步骤2:编写查询工具函数
创建app-config-resolver.ts:
import { AppConfigClient, ListApplicationsCommand, ListEnvironmentsCommand, ListConfigurationProfilesCommand } from '@aws-sdk/client-appconfig'; import { APP_REGION, APP_CONFIG_APP_NAME } from './config'; const appConfigClient = new AppConfigClient({ region: APP_REGION }); // 根据应用名称获取应用ID export async function getAppIdByName(appName: string): Promise<string> { const command = new ListApplicationsCommand({}); const response = await appConfigClient.send(command); const app = response.Items?.find(item => item.Name === appName); if (!app?.Id) throw new Error(`AppConfig application ${appName} not found`); return app.Id; } // 根据应用ID和环境名称获取环境ID export async function getEnvIdByAppAndName(appId: string, envName: string): Promise<string> { const command = new ListEnvironmentsCommand({ ApplicationId: appId }); const response = await appConfigClient.send(command); const env = response.Items?.find(item => item.Name === envName); if (!env?.Id) throw new Error(`AppConfig environment ${envName} not found for app ${appId}`); return env.Id; } // 根据应用ID和配置文件名称获取配置文件ID export async function getProfileIdByAppAndName(appId: string, profileName: string): Promise<string> { const command = new ListConfigurationProfilesCommand({ ApplicationId: appId }); const response = await appConfigClient.send(command); const profile = response.Items?.find(item => item.Name === profileName); if (!profile?.Id) throw new Error(`AppConfig profile ${profileName} not found for app ${appId}`); return profile.Id; }
步骤3:修改app-config-client.ts使用动态ID
import { AppConfigDataClient, StartConfigurationSessionCommand } from '@aws-sdk/client-appconfigdata'; import { APP_REGION, APP_CONFIG_APP_NAME } from '../../../config'; import { getAppIdByName, getEnvIdByAppAndName, getProfileIdByAppAndName } from './app-config-resolver'; const client = new AppConfigDataClient({ region: APP_REGION }); export async function getToken(): Promise<string> { try{ // 动态获取各标识符 const appId = await getAppIdByName(APP_CONFIG_APP_NAME); const envName = process.env.APP_CONFIG_ENV_NAME || 'staging'; const envId = await getEnvIdByAppAndName(appId, envName); const profileName = process.env.APP_CONFIG_PROFILE_NAME || 'default'; const profileId = await getProfileIdByAppAndName(appId, profileName); const getSession = new StartConfigurationSessionCommand ({ ApplicationIdentifier: appId, EnvironmentIdentifier: envId, ConfigurationProfileIdentifier: profileId, }); const sessionToken = await client.send(getSession); return sessionToken.InitialConfigurationToken || ""; } catch (err) { console.error('Error retrieving session token: ', err); throw err; } }
权限说明
给应用的IAM角色添加以下权限:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "appconfig:ListApplications", "appconfig:ListEnvironments", "appconfig:ListConfigurationProfiles" ], "Resource": "*" } ] }
方案3:解析ARN获取标识符
如果基础设施已经输出AppConfig配置文件的ARN,可通过解析ARN提取各标识符。ARN格式为:arn:aws:appconfig:<region>:<account-id>:application/<app-id>/environment/<env-id>/configurationprofile/<profile-id>
编写ARN解析函数
export function parseAppConfigArn(arn: string): { appId: string, envId: string, profileId: string } { const parts = arn.split('/'); if (parts.length < 6) throw new Error('Invalid AppConfig ARN'); return { appId: parts[2], envId: parts[4], profileId: parts[6] }; }
使用示例
// 从环境变量获取ARN const appConfigArn = process.env.APP_CONFIG_ARN || ''; const { appId, envId, profileId } = parseAppConfigArn(appConfigArn); // 传入StartConfigurationSessionCommand const getSession = new StartConfigurationSessionCommand ({ ApplicationIdentifier: appId, EnvironmentIdentifier: envId, ConfigurationProfileIdentifier: profileId, });
内容的提问来源于stack exchange,提问作者Tiffany Doan
相关产品推荐
相关产品推荐

