Cấu Hình Runtime
Cấu hình runtime là cơ chế được Nx Plugin for AWS sử dụng để truyền các giá trị tại thời điểm triển khai giữa các dự án và thành phần được tạo để chúng có thể kết nối với nhau. Ví dụ, khi bạn tạo một API, URL của nó sẽ tự động được đăng ký trong cấu hình runtime để một website được kết nối có thể khám phá nó.
Cách Hoạt Động
Phần tiêu đề “Cách Hoạt Động”Cấu hình runtime được tổ chức thành các namespace. Mỗi namespace là một nhóm logic của các giá trị cấu hình liên quan. Tại thời điểm triển khai, tất cả các namespace được lưu trữ trong AWS AppConfig dưới dạng Configuration Profiles.
Bốn namespace tích hợp sẵn được sử dụng bởi các construct được tạo:
connection— cấu hình cho phép các dự án được tạo kết nối với nhau:- API URLs — được đăng ký tự động bởi các construct API
- Cognito settings — được đăng ký tự động bởi construct UserIdentity
- Agent runtime ARNs — được thêm bởi trình tạo kết nối khi bạn kết nối một website React với một Agent
agentcore— AgentCore runtime ARNs cho các agent và MCP server. Được đăng ký tự động bởi các construct agent/MCP và được sử dụng để khám phá phía server (agent → agent qua A2A, agent → MCP server).dynamodb— tên bảng, được đăng ký tự động bởi các construct bảng DynamoDB và được đọc bởi table client được tạo.database— chi tiết kết nối Aurora, được đăng ký tự động bởi các construct cơ sở dữ liệu quan hệ và được đọc bởi database client được tạo.
Namespace connection cũng được triển khai dưới dạng file runtime-config.json vào S3 bucket của website của bạn, cho phép khám phá các tài nguyên backend từ phía client. Các namespace khác chỉ dành cho phía server (qua AppConfig), vì vậy các giá trị như agent runtime ARN và tên bảng không được tiết lộ cho frontend trừ khi bạn kết nối rõ ràng một website với chúng.
Bạn có thể định nghĩa bao nhiêu namespace bổ sung tùy thích, cung cấp một giải pháp thay thế thuận tiện cho các biến môi trường để truyền các giá trị tại thời điểm triển khai cho các hàm Lambda hoặc tài nguyên tính toán khác của bạn.
Infrastructure
Phần tiêu đề “Infrastructure”Ghi Cấu Hình
Phần tiêu đề “Ghi Cấu Hình”Các construct được tạo tự động ghi cấu hình liên quan vào namespace connection. Bạn cũng có thể ghi các giá trị của riêng mình vào bất kỳ namespace nào.
Construct CDK RuntimeConfig là một singleton có phạm vi stage. Sử dụng set() để ghi một key vào một namespace:
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 configurationrc.set('tables', 'users', { tableName: usersTable.tableName, tableArn: usersTable.tableArn,});Tại thời điểm synth/deploy, RuntimeConfig tạo một ứng dụng AWS AppConfig chứa:
- Một Configuration Profile cho mỗi namespace
- Một Hosted Configuration Version với dữ liệu JSON cho mỗi profile
- Một Deployment tức thì vào môi trường
default
Terraform kết nối cấu hình runtime qua ba module core/runtime-config/*. Khai báo chúng theo thứ tự sau trong root module của bạn:
-
core/runtime-config/appconfig— được khai báo một lần, gần đầu root module. Tạo ứng dụng AppConfig, môi trường, chiến lược triển khai và một configuration profile cho mỗi namespace. Các outputapplication_idvàapplication_arncủa nó được truyền vào mọi module đọc cấu hình runtime tại runtime (agent, MCP server, hàm Lambda, v.v.).packages/infra/src/main.tf module "runtime_config_appconfig" {source = "../../common/terraform/src/core/runtime-config/appconfig"application_name = "my-app-runtime-config"}Biến
namespacesmặc định là mọi namespace tích hợp sẵn, vì vậy các module được tạo hoạt động mà không cần cấu hình nó. Để thêm các namespace của riêng bạn, liệt kê chúng cùng với các namespace tích hợp sẵn:packages/infra/src/main.tf module "runtime_config_appconfig" {source = "../../common/terraform/src/core/runtime-config/appconfig"application_name = "my-app-runtime-config"namespaces = ["connection", "agentcore", "database", "dynamodb", "tables"]} -
core/runtime-config/entry— một lần gọi cho mỗi đóng góp. Các module API, agent và MCP được tạo gọi nó nội bộ để xuất bản URL và ARN của chúng. Gọi trực tiếp để xuất bản cấu hình tùy chỉnh.packages/infra/src/main.tf # Automatic — done inside generated modulesmodule "add_api_url" {source = "../../common/terraform/src/core/runtime-config/entry"namespace = "connection"key = "apis"value = { "MyApi" = module.my_api.api_url }}# Custom namespace for server-side configurationmodule "add_table_config" {source = "../../common/terraform/src/core/runtime-config/entry"namespace = "tables"key = "users"value = {tableName = aws_dynamodb_table.users.namearn = aws_dynamodb_table.users.arn}} -
core/runtime-config/appconfig-deployment— được khai báo một lần, ở cuối root module, vớidepends_onbao gồm mọi module đóng góp một entry. Tổng hợp các entry được đóng góp thành một JSON cho mỗi namespace và tạo hosted configuration version + deployment đối với ứng dụng được chia sẻ.packages/infra/src/main.tf module "runtime_config_appconfig_deployment" {source = "../../common/terraform/src/core/runtime-config/appconfig-deployment"application_id = module.runtime_config_appconfig.application_idenvironment_id = module.runtime_config_appconfig.environment_iddeployment_strategy_id = module.runtime_config_appconfig.deployment_strategy_idconfiguration_profile_ids = module.runtime_config_appconfig.configuration_profile_idsnamespaces = module.runtime_config_appconfig.namespacesdepends_on = [module.my_api,module.add_table_config,# ...every module that contributes an entry]}
Đọc Cấu Hình
Phần tiêu đề “Đọc Cấu Hình”Các consumer phía server cần AppConfig Application ID và quyền IAM để đọc cấu hình tại runtime. Các construct được tạo xử lý điều này tự động.
Sử dụng appConfigApplicationId để lấy AppConfig Application ID, và grantReadAppConfig() để cấp quyền đọc:
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 functionconst myFunction = new Function(this, 'MyFunction', { // ... environment: { RUNTIME_CONFIG_APP_ID: appId, },});
// Grant the function permission to read from AppConfigrc.grantReadAppConfig(myFunction);Tham chiếu output application_id của module runtime_config_appconfig được chia sẻ để lấy AppConfig Application ID, và thêm các câu lệnh IAM policy thích hợp:
# Pass the AppConfig Application ID as an environment variableresource "aws_lambda_function" "my_function" { # ... environment { variables = { RUNTIME_CONFIG_APP_ID = module.runtime_config_appconfig.application_id } }}
# Grant the function permission to read from AppConfigresource "aws_iam_policy" "appconfig_read" { name = "AppConfigReadPolicy" policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Action = [ "appconfig:StartConfigurationSession", "appconfig:GetLatestConfiguration" ] Resource = ["${module.runtime_config_appconfig.application_arn}/*"] }] })}Truy Cập Phía Server qua AppConfig
Phần tiêu đề “Truy Cập Phía Server qua AppConfig”Các consumer phía server như hàm Lambda và agent có thể truy xuất cấu hình runtime từ AWS AppConfig bằng cách sử dụng AWS Lambda Powertools.
Tất cả các construct API và agent được tạo đều được cấu hình tự động với:
- Biến môi trường
RUNTIME_CONFIG_APP_ID(AppConfig Application ID) - Quyền IAM để đọc từ AppConfig
Sử dụng getAppConfig từ @aws-lambda-powertools/parameters:
import { getAppConfig } from '@aws-lambda-powertools/parameters/appconfig';
// Retrieve the 'connection' namespace as a parsed JSON objectconst config = await getAppConfig('connection', { application: process.env.RUNTIME_CONFIG_APP_ID!, environment: 'default', transform: 'json',});
// Access valuesconst apiUrl = config.apis?.MyApi;const cognitoProps = config.cognitoProps;Bạn cũng có thể truy xuất các namespace tùy chỉnh:
// Retrieve a custom 'tables' namespaceconst tablesConfig = await getAppConfig('tables', { application: process.env.RUNTIME_CONFIG_APP_ID!, environment: 'default', transform: 'json',});
const usersTableName = tablesConfig.users?.tableName;Sử dụng get_app_config từ aws_lambda_powertools.utilities.parameters:
import osfrom aws_lambda_powertools.utilities import parameters
# Retrieve the 'connection' namespace as a parsed JSON objectconfig = parameters.get_app_config( name="connection", environment="default", application=os.environ["RUNTIME_CONFIG_APP_ID"], transform="json",)
# Access valuesapi_url = config.get("apis", {}).get("MyApi")cognito_props = config.get("cognitoProps")Bạn cũng có thể truy xuất các namespace tùy chỉnh:
# Retrieve a custom 'tables' namespacetables_config = parameters.get_app_config( name="tables", environment="default", application=os.environ["RUNTIME_CONFIG_APP_ID"], transform="json",)
users_table_name = tables_config.get("users", {}).get("tableName")Truy Cập Phía Client
Phần tiêu đề “Truy Cập Phía Client”Đối với các website, namespace connection được triển khai dưới dạng file runtime-config.json vào S3 bucket. Xem hướng dẫn React Website Runtime Configuration để biết chi tiết về cách truy cập các giá trị này từ mã frontend của bạn.