跳转到内容
AggregaAggrega
选择语言: 简体中文
本页面由机器翻译。阅读英文原文。

托管数据库及读取它的服务,基于 Terraform 和 CloudFormation

一个 Aggregate 包含一个 PostgreSQL 数据库和读取它的服务器。同一个 Aggregate 针对 AWS 以三种方式构建:作为一个 Terraform 根配置, 数据库由 terraform-aws-modules 项目发布的 RDS 模块预配, 服务器作为 Fargate 上的 Amazon ECS 服务运行;作为一个同时包含两者的 CloudFormation 栈;以及作为两个 CloudFormation 栈,数据库在一个栈中,服务器在另一个栈中。

在每个目标上,服务器以该目标自身解析的形式接收数据库地址: 在根配置中是模块输出引用,在单个栈内是 Fn::GetAtt,跨两个栈是 Fn::ImportValue。 编译器不对其中任何一个求值。实例创建之前地址并不存在, 因此构建过程将引用原样传递,由目标在部署时解析。

本页的输出块复制自一次真实运行,参见 阅读这些页面上的输出。

文件

  • aggregate.yaml — 开发者意图:一个类型为 core/datastore/postgres 的 db 组件,其中包含一个由角色 orders_admin 拥有的逻辑数据库 orders;以及一个类型为 core/compute/server 的 api 组件, 它使用该数据库。其中没有任何键或值与 AWS 相关。
  • manifest-terraform.yaml — 将数据库绑定到 Recipe terraform/postgres-rds-terraform-aws-modules,将服务器绑定到 terraform/server-ecs,并将 core/backup Feature 绑定到 terraform/backup-native。
  • manifest-cloudformation.yaml — 将数据库绑定到 cloudformation/postgres-rds,将服务器绑定到 cloudformation/server-ecs,并将 core/backup Feature 绑定到 cloudformation/backup-native。
  • release-terraform.yaml — 两个组件位于同一个边界内,通过 Terraform Manifest 构建。
  • release-one-stack.yaml — 两个组件位于同一个边界内,通过 CloudFormation Manifest 构建,因此两者组装进单个栈。
  • release-two-stacks.yaml — 同一意图拆分到两个边界中,因此 服务器对数据库的引用会跨越栈的边界。
  • .aggrega-config.yaml —— 指定标准库目录从中解析的 hub 注册表。

本示例使用的实体全部位于该目录中。没有任何内容被复制到 release 文件旁边。

服务器请求什么

服务器在一个名为 database 的套接字上声明一条边,并请求数据库发布的条目中的四个,使用其自身配置所读取的环境变量名称:

api:
type: core/compute/server
uses:
database:
db:
target: db
inject:
env:
- in: DB_HOST
from: host
- in: DB_PORT
from: port
- in: DB_USER
from: user
- in: DB_NAME
from: database

core/compute/server 自身未声明任何套接字,因此 database 是一个临时套接字:该边不带选择器,也不带注入允许列表,而每个 from: 键仍必须是数据库所发布的键——该约束见 adhoc-uses-socket。该 Aggregate 从不指定地址、端口号或云服务提供商,并且对下面的全部三种构建而言都是同一个文件。

运维人员提供的内容

每个 Release 都在 infra.overrides 下列出运维人员已在运行、供 Recipes 读取的资源:RDS 数据库子网组和数据库的安全组,以及 ECS 集群、任务所接入的子网和安全组,还有 ECS 用于拉取镜像和写入日志的执行角色。服务器的镜像为 infra.image。两个服务器 Recipes 都要求提供镜像、集群、子网、安全组和执行角色,Terraform 数据库 Recipe 还要求提供子网组:缺少其中任何一项的构建会停止并指出该键,而不会替你选择网络或角色。

这些值全部是占位符——123456789012 是 AWS 文档在示例中使用的账号,而 example-cluster、example-private-db-subnets、subnet-… 和 sg-… ID、角色以及 registry.example.com/orders-api:1.0.0 代表你自己账号中的资源。 构建之所以接受它们,是因为构建从不查询这些资源;在执行 plan 或部署之前,请先替换它们。

Terraform Recipes 按目录的 terraform 写法读取这些键(subnet_group、subnet_ids、vpc_security_groups、cluster、execution_role_arn);CloudFormation Recipes 则按资源属性自身的名称读取(DBSubnetGroupName、VPCSecurityGroups、Cluster、Subnets、SecurityGroups、ExecutionRoleArn),因此同样的运维值在两个目标上的写法不同。

生成示例

你可以用下面的命令构建这个示例,也可以让你的 AI 助手替你构建。

将示例写入一个以其命名的新文件夹:

Terminal window
aggrega scaffold --example aws-rds-and-ecs-service

然后它会打印接下来要运行的命令。第一条命令进入新文件夹:

Terminal window
cd aws-rds-and-ecs-service

构建

本示例包含三个 release,因此请指定你要构建的那个。每次运行只构建一个 release。在全新的副本中,每个 release 第一次构建时,请传入 --auto-pull,以便在构建过程中填充其锁文件。首次 Terraform 构建会从 RDS 模块的 git 仓库获取该模块,所取的提交即该 Recipe 自身的固定版本所记录的提交:

Terminal window
aggrega build --release release-terraform.yaml --auto-pull

输出如下,其中 <workspace> 代表本示例所在的文件夹:

Pull complete: release-terraform.lock (entities=11, source_artifacts=1, external_inputs=0)
Total build time: 9.4s
Build completed: 151 files written to <workspace>/dist

锁文件存在后,直接运行普通命令即可基于它进行构建:

Terminal window
aggrega build --release release-terraform.yaml
Total build time: 5.7s
Build completed: 151 files written to <workspace>/dist

借助 AI 助手

已配置 Aggrega 工具的 AI 助手也能完成同样的操作:把下面这条提示粘贴给它。

只使用 Aggrega 的工具,不要自己创建任何文件夹。如果工作区文件夹中还没有 `aws-rds-and-ecs-service` 文件夹,就调用一次 `scaffold` 工具,将 `example` 设为 `aws-rds-and-ecs-service`,且不提供 `dir`:它会把示例写入一个新的 `aws-rds-and-ecs-service` 文件夹。然后调用 `build` 工具,将 `workspace_root` 设为 `aws-rds-and-ecs-service`,`release` 设为 `release-terraform.yaml`,`auto_pull` 设为 true,`write` 设为 true。告诉我构建写入了哪些文件;它们位于 `aws-rds-and-ecs-service/dist/` 下。

一个 Terraform 根配置

该边界的根配置生成于 dist/one-root/terraform/aggrega.modules.tf,每个组件自己的文件位于其 module 块所指向的目录中: 内置的 RDS 模块位于 modules/db/ 下,而服务器的 ECS 模块(在目录中与其 Recipe 放在一起)位于 modules/api/ 下。完整的根配置:

# Root configuration for this boundary. Each component rendered here is one
# module block below, and the directory that block points at holds that
# component's own files. One configuration means one dependency graph, which is
# what lets a reference or a depends_on reach from one component to another.
module "api" {
source = "./modules/api"
assign_public_ip = false
cluster = "example-cluster"
cpu = "256"
desired_count = 2
environment = {"DB_HOST":"${module.db.db_instance_address}","DB_NAME":"orders","DB_PORT":"5432","DB_USER":"orders_admin"}
execution_role_arn = "arn:aws:iam::123456789012:role/example-ecs-task-execution"
image = "registry.example.com/orders-api:1.0.0"
memory = "512"
name = "api"
port = 8080
security_groups = ["sg-0fedcba9876543210"]
subnet_ids = ["subnet-0123456789abcdef0","subnet-0fedcba9876543210"]
}
module "db" {
source = "./modules/db"
allocated_storage = 50
backup_retention_period = 14
create_db_subnet_group = false
db_name = "orders"
db_subnet_group_name = "example-private-db-subnets"
engine = "postgres"
engine_version = "16"
family = "postgres16"
identifier = "db"
instance_class = "db.t3.small"
manage_master_user_password = true
multi_az = true
port = "5432"
skip_final_snapshot = false
storage_type = "gp3"
username = "orders_admin"
vpc_security_group_ids = ["sg-0123456789abcdef0"]
}

服务器的 environment 参数承载边缘所请求的四个值。DB_HOST 为 ${module.db.db_instance_address}:数据库 Recipe 通过同一根配置中声明为 module "db" 的模块调用,发布对 RDS 模块自身 db_instance_address 输出的引用,因此 Terraform 在此处于 plan 和 apply 时对其求值,服务器的模块则将该实例的地址作为普通输入接收。其余三个值是编译器预先已知的纯文本——Release 配置的端口,以及 Aggregate 写入的两个名称。

之所以可行,是因为服务器的 Recipe 是一个 source: Recipe:其映射成为服务器 module 块的参数,而这是 Terraform 在声明了相邻模块的作用域中求值的唯一位置——其机制,以及使用方将引用写在其他位置时会出现的问题,参见 使用另一个组件发布的值 和一个完整的配对示例。出于同样的原因,应对此目录(即包含 aggrega.modules.tf 的目录)执行 plan,而不是单独对任一模块目录执行。

在该目录的临时副本上,tofu init -backend=false 从磁盘加载根配置 和内置模块,并且只获取 provider:

Initializing modules...
- api in modules/api
- db in modules/db
- db.db_instance in modules/db/modules/db_instance
- db.db_instance_role_association in modules/db/modules/db_instance_role_association
- db.db_option_group in modules/db/modules/db_option_group
- db.db_parameter_group in modules/db/modules/db_parameter_group
- db.db_subnet_group in modules/db/modules/db_subnet_group
[… omitted: provider installation, whose versions move with the registry, and OpenTofu's closing advice]

随后 tofu validate 输出:

Success! The configuration is valid.

一个 CloudFormation 栈

Terminal window
aggrega build --release release-one-stack.yaml --auto-pull
Pull complete: release-one-stack.lock (entities=11, source_artifacts=0, external_inputs=0)
Total build time: 6.2s
Build completed: 1 file written to <workspace>/dist

组装后的栈位于 dist/one-stack/cloudformation/cloudformation-stack.json,包含三个资源:Db,即 RDS 实例;Api,即 ECS 服务;以及 ApiTaskDefinition,即该服务运行的任务定义。ApiTaskDefinition 中容器的环境变量:

"Environment": [
{
"Name": "DB_HOST",
"Value": {
"Fn::GetAtt": [
"Db",
"Endpoint.Address"
]
}
},
{
"Name": "DB_NAME",
"Value": "orders"
},
{
"Name": "DB_PORT",
"Value": "5432"
},
{
"Name": "DB_USER",
"Value": "orders_admin"
}
],

DB_HOST 是对实例 Endpoint.Address 的 Fn::GetAtt,作用于数据库 Recipe 根据组件名 db 派生出的逻辑 ID Db。 CloudFormation 在创建栈时解析它;由于服务器的任务定义读取 Db 的一个属性,CloudFormation 会先创建该实例。参见 栈内引用。

两个 CloudFormation 栈

Terminal window
aggrega build --release release-two-stacks.yaml --auto-pull
Pull complete: release-two-stacks.lock (entities=11, source_artifacts=0, external_inputs=0)
Total build time: 6.2s
Build completed: 2 files written to <workspace>/dist

aggregate.yaml 没有任何改动。该 Release 将数据库放在 data 边界中,将服务器放在 app 边界中,因此二者各自组装为独立的栈,服务器指向数据库的边从一个栈跨越到另一个栈。数据库的栈 dist/two-stacks-data/cloudformation/cloudformation-stack.json 将该边消费的每个条目发布为带有 Export 的输出。其 Outputs:

"Outputs": {
"dbXXdatabase": {
"Value": "orders",
"Export": {
"Name": "aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--database"
}
},
"dbXXhost": {
"Value": {
"Fn::GetAtt": [
"Db",
"Endpoint.Address"
]
},
"Export": {
"Name": "aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--host"
}
},
"dbXXport": {
"Value": "5432",
"Export": {
"Name": "aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--port"
}
},
"dbXXprotocol": {
"Value": "postgres"
},
"dbXXuser": {
"Value": "orders_admin",
"Export": {
"Name": "aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--user"
}
}
},

protocol 同样会被发布,但由于没有边读取它,因此不带 Export。服务器的栈 dist/two-stacks-app/cloudformation/cloudformation-stack.json 按相同名称读回这四个条目中的每一个:

"Environment": [
{
"Name": "DB_HOST",
"Value": {"Fn::ImportValue":"aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--host"}
},
{
"Name": "DB_NAME",
"Value": {"Fn::ImportValue":"aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--database"}
},
{
"Name": "DB_PORT",
"Value": {"Fn::ImportValue":"aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--port"}
},
{
"Name": "DB_USER",
"Value": {"Fn::ImportValue":"aggrega--orders-two-stacks--two-stacks-data-zscloudformation--db--user"}
}
],

每个导出名称由 Release 名称、生产者边界的输出目录、组件和条目拼接而成,因此它在构建时即已确定,消费者可以在任何一个栈存在之前就引用它。这里的两个 Release 都没有声明账户或区域,因此读取方式是同账户的 Fn::ImportValue。名称如何构建,以及消费者何时改为跨账户读取,详见跨栈连接。导入只能解析已经存在的导出,因此数据库的栈要先于服务器的栈创建;这两个栈的创建顺序由运维人员负责,不在构建范围之内。

密码归 RDS 自身管理

该 Aggregate 只指定了数据库的用户,未涉及其密码,也没有任何 Release 为数据库附加凭据。在两个目标上,Manifest 选中的 Recipe 都将密码交给 RDS 管理:在上文的模块块中为 manage_master_user_password = true,在每个栈的实例上为 ManageMasterUserPassword。单栈模板中数据库的 Properties:

"Properties": {
"AllocatedStorage": 50,
"BackupRetentionPeriod": 14,
"DBInstanceClass": "db.t3.small",
"DBName": "orders",
"DBSubnetGroupName": "example-private-db-subnets",
"Engine": "postgres",
"EngineVersion": "16",
"ManageMasterUserPassword": true,
"MasterUsername": "orders_admin",
"MultiAZ": true,
"Port": 5432,
"StorageType": "gp3",
"VPCSecurityGroups": [
"sg-0123456789abcdef0"
]
},

RDS 在创建实例时生成管理员密码,并将其保存在 AWS Secrets Manager 中。没有任何构建输入携带密码,因此三次构建都不会把密码写入任何文件。服务器接收用户名而不接收其密码;从 Secrets Manager 读取密码的工作留给服务器镜像所运行的代码。

备份是一个附件

在没有其他设置时,RDS 会自行备份实例,并将每个自动备份保留 7 天。每个 Release 都通过在其 db 条目上把 core/backup 附加到数据库,将备份保留 14 天:

db:
features:
backup:
type: core/backup
infra:
retention_days: 14

每个 Manifest 都把该 Feature 绑定到其目标对应的 FeatureRecipe,即 terraform/backup-native 或 cloudformation/backup-native,二者都不渲染任何内容:备份是实例的一项设置,因此数据库 Recipe 读取该附件,并在写入实例的地方写入保留期——模块块上的 backup_retention_period = 14,以及上文实例 Properties 中的 "BackupRetentionPeriod": 14。这就是单栈模板恰好包含三个资源的原因。

构建不等于部署

每次构建都会在 dist/ 下写入文件,然后停止。它从不运行 Terraform、OpenTofu 或 CloudFormation,从不向 AWS 进行身份验证,也不查找 Releases 所指定的任何标识符。规划和应用根配置、创建这些堆栈,都是你在替换占位符之后,使用自己的凭据对输出执行的步骤。

相同的输入,相同的输出

在输入未变的情况下构建两次,三个 release 各自产生字节完全相同的输出。编译器不解析任何实时数据,因此重新构建不会发现任何可能改变字节的内容。基于 diff 的审查所依赖的正是这一特性。

dist/、.aggrega/ 和 *.lock 文件是生成的,不会提交;它们可以从已提交的文件重新生成。