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——把資料庫繫結到 Recipeterraform/postgres-rds-terraform-aws-modules,把伺服器繫結到terraform/server-ecs,並把core/backupFeature 繫結到terraform/backup-native。manifest-cloudformation.yaml——把資料庫繫結到cloudformation/postgres-rds,把伺服器繫結到cloudformation/server-ecs,並把core/backupFeature 繫結到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: databasecore/compute/server 不宣告自己的插槽,因此 database 是臨機插槽:該邊不帶選擇器,也不帶 inject 允許清單,而每個 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 代表你自己帳戶中的資源。建置接受它們,因為它從不查詢它們;在你規劃或部署之前請替換它們。
Terraform Recipes 以目錄的 terraform 拼法讀取它們的鍵(subnet_group、subnet_ids、vpc_security_groups、cluster、execution_role_arn);CloudFormation Recipes 以資源屬性自己的名稱讀取它們(DBSubnetGroupName、VPCSecurityGroups、Cluster、Subnets、SecurityGroups、ExecutionRoleArn),因此相同的操作員值在兩個目標上的拼法不同。
草擬範例
你可以用下列命令建置這個範例,或是讓你的 AI 助理替你建置。
把範例寫入一個以它命名的新資料夾:
aggrega draft --example aws-rds-and-ecs-service它接著會印出要接著執行的命令。第一個會切換到新資料夾:
cd aws-rds-and-ecs-service建置
此範例隨附三個 Releases,所以請指名你要的那一個。每次執行建置一個 Release。在全新的副本中,第一次建置每個 Release 時傳入 --auto-pull,使其鎖定檔在建置期間被填入。第一次 Terraform 建置會從其 git 存放庫取得 RDS 模組,使用 Recipe 自己的固定所記錄的提交:
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.4sBuild completed: 151 files written to <workspace>/dist鎖定檔存在之後,一般的命令就依它建置:
aggrega build --release release-terraform.yamlTotal build time: 5.7sBuild completed: 151 files written to <workspace>/dist搭配 AI 助理
以 Aggrega 的工具設定好的 AI 助理可以做同樣的事:把這個提示貼給它。
只使用 Aggrega 工具,且不要自行建立任何資料夾。若工作區資料夾中還沒有 `aws-rds-and-ecs-service` 資料夾,請呼叫 `draft` 工具一次,將 `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 區塊所指向的目錄中:vendored 的 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 發布一個參照,指向 RDS 模組自己的 db_instance_address 輸出,經由此根同樣宣告為 module "db" 的模組呼叫,因此 Terraform 在這裡於規劃與套用時求值,而伺服器的模組把執行個體的位址當作一般輸入收到。其他三個是編譯器事先已知的純文字——Release 所設定的連接埠,以及 Aggregate 所寫的兩個名稱。
這之所以可行,是因為伺服器的 Recipe 是 source: Recipe:它的對應成為伺服器 module 區塊的引數,這是 Terraform 在鄰近模組已宣告的範圍中求值的唯一位置——機制請見取用另一個元件發布的值與一組實作範例,以及使用端把參照寫在其他任何位置時會出什麼問題。基於同樣的原因,請規劃此目錄——包含 aggrega.modules.tf 的那個——而不是單獨規劃任一個模組目錄。
在該目錄的暫存副本上,tofu init -backend=false 從磁碟載入根與 vendored 的模組,且只取得提供者:
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 堆疊
aggrega build --release release-one-stack.yaml --auto-pullPull complete: release-one-stack.lock (entities=11, source_artifacts=0, external_inputs=0)Total build time: 6.2sBuild 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 堆疊
aggrega build --release release-two-stacks.yaml --auto-pullPull complete: release-two-stacks.lock (entities=11, source_artifacts=0, external_inputs=0)Total build time: 6.2sBuild completed: 2 files written to <workspace>/distaggregate.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 所指名的任何識別碼。規劃並套用根設定,以及建立堆疊,是你在輸出上以自己的認證、在替換預留位置之後所採取的步驟。
相同的輸入,相同的輸出
從未變更的輸入建置兩次,會對三個 Releases 各自產生逐位元組相同的輸出。編譯器不解析任何即時資料,因此重新建置沒有任何可探索而會使位元組改變的東西。這就是以差異為基礎的審查所依賴的性質。
dist/、.aggrega/ 與 *.lock 檔是產生的,不會提交;它們由已提交的檔案重新產生。