跳转到内容

运行时配置

运行时配置是 Nx Plugin for AWS 用于在生成的项目和组件之间传递部署时值的机制,以便它们可以相互连接。例如,当您生成一个 API 时,其 URL 会自动注册到运行时配置中,以便连接的网站可以发现它。

运行时配置被组织成命名空间。每个命名空间是相关配置值的逻辑分组。在部署时,所有命名空间都作为配置文件存储在 AWS AppConfig 中。

内置的 connection 命名空间用于使生成的项目能够相互连接的配置,例如:

  • API URLs — 由 API 构造自动注册
  • Cognito settings — 由 UserIdentity 构造自动注册
  • Agent runtime ARNs — 由 agent 构造自动注册

connection 命名空间还会作为 runtime-config.json 文件部署到您网站的 S3 存储桶中,从而使客户端能够发现后端资源。

您可以定义任意数量的附加命名空间,为传递部署时值(例如 DynamoDB 表名)到 Lambda 函数或其他计算资源提供了一种便捷的环境变量替代方案。

生成的构造会自动将相关配置写入 connection 命名空间。您也可以将自己的值写入任何命名空间。

RuntimeConfig CDK 构造是一个阶段范围的单例。使用 set() 将键写入命名空间:

packages/infra/src/stacks/application-stack.ts
import { RuntimeConfig } from ':my-scope/common-constructs';
const rc = RuntimeConfig.ensure(this);
// Built-in 'connection' namespace (written automatically by generated constructs)
rc.set('connection', 'apis', {
...rc.get('connection').apis,
MyApi: api.url,
});
// Custom namespaces for server-side configuration
rc.set('tables', 'users', {
tableName: usersTable.tableName,
tableArn: usersTable.tableArn,
});

在合成/部署时,RuntimeConfig 会创建一个包含以下内容的 AWS AppConfig 应用程序:

  • 每个命名空间的 Configuration Profile
  • 每个配置文件的 JSON 数据的 Hosted Configuration Version
  • default 环境的即时 Deployment

服务器端消费者需要 AppConfig Application ID 和 IAM 权限才能在运行时读取配置。生成的构造会自动处理这些。

使用 appConfigApplicationId 获取 AppConfig Application ID,并使用 grantReadAppConfig() 授予读取权限:

packages/infra/src/stacks/application-stack.ts
const rc = RuntimeConfig.ensure(this);
// Get the AppConfig Application ID (lazy token, resolved at synth time)
const appId = rc.appConfigApplicationId;
// Pass it as an environment variable to a Lambda function
const myFunction = new Function(this, 'MyFunction', {
// ...
environment: {
RUNTIME_CONFIG_APP_ID: appId,
},
});
// Grant the function permission to read from AppConfig
rc.grantReadAppConfig(myFunction);

Lambda 函数和 agent 等服务器端消费者可以使用 AWS Lambda PowertoolsAWS AppConfig 检索运行时配置。

所有生成的 API 和 agent 构造都会自动配置:

  • RUNTIME_CONFIG_APP_ID 环境变量(AppConfig Application ID)
  • 从 AppConfig 读取的 IAM 权限

使用 @aws-lambda-powertools/parameters 中的 getAppConfig:

import { getAppConfig } from '@aws-lambda-powertools/parameters/appconfig';
// Retrieve the 'connection' namespace as a parsed JSON object
const config = await getAppConfig('connection', {
application: process.env.RUNTIME_CONFIG_APP_ID!,
environment: 'default',
transform: 'json',
});
// Access values
const apiUrl = config.apis?.MyApi;
const cognitoProps = config.cognitoProps;

您还可以检索自定义命名空间:

// Retrieve a custom 'tables' namespace
const tablesConfig = await getAppConfig('tables', {
application: process.env.RUNTIME_CONFIG_APP_ID!,
environment: 'default',
transform: 'json',
});
const usersTableName = tablesConfig.users?.tableName;

对于网站,connection 命名空间会作为 runtime-config.json 文件部署到 S3 存储桶。有关如何从前端代码访问这些值的详细信息,请参阅 React Website Runtime Configuration 指南。