Перейти до вмісту
AggregaAggregaAggregaAggrega
Обрати мову: Українська
Цю сторінку перекладено машинним способом. Читати оригінал англійською.

Розгортання сервісу, якого немає в каталозі

Коли каталог не містить Component для хмарного сервісу, його може замінити власний опис типу ресурсу цього сервісу від вендора. aggrega import читає цей опис — схему, яку хмарний вендор публікує для типу ресурсу, — і створює з нього два файли: Component, який оголошує налаштування цього типу в стовпах, що їх читає Aggrega, і Recipe, який реалізує Component для провайдера, записуючи рівно один ресурс цього типу. Ви переглядаєте чернетки, додаєте рядки, які їх використовують, до Aggregate і Release та запускаєте збірку.

Читаються три формати, кожен — базовим імпортером, який його обслуговує:

ФорматСхема, яку ви експортуєтеПровайдер Recipe
cloudformation-schemaтип ресурсу CloudFormation, з aws cloudformation describe-type або з файлу схеми провайдераcloudformation
terraform-schemaсхема провайдера Terraform або OpenTofu, з terraform providers schema -jsonterraform
arm-schemaфайл типів Bicep постачальника ресурсів Azure, types.jsonarm

Ця сторінка докладно розбирає випадок Azure від початку до кінця, а потім показує випадки CloudFormation і Terraform та варіант, який створює чернетку лише Recipe для Component, що вже є в каталозі. Команди та виведення в частинах про Azure нижче взято із запуску збірки релізу компілятора, який містить ці імпортери та провайдер arm.

Нічого не завантажується від вашого імені. Ви експортуєте схему власним інструментом вендора, тож імпорт читає файл, який у вас є, і не звертається до жодного хмарного облікового запису.

Експорт схеми

Інструмент кожного вендора записує схему у файл. Запустіть той, що відповідає вашій хмарі, у робочому просторі:

Terminal window
# CloudFormation: any registered type, third-party and private ones included.
aws cloudformation describe-type --type RESOURCE --type-name AWS::SQS::Queue > sqs-queue.json
# Terraform or OpenTofu: in a directory whose configuration requires the provider.
terraform init && terraform providers schema -json > schema.json
# Azure: no export is needed. Bicep's type files are published in the
# Azure/bicep-types-az repository, one for each resource provider and API
# version, at generated/<namespace>/<provider>/<apiVersion>/types.json.

Випадок Azure нижче використовує файл для Microsoft.ManagedIdentity з версією API 2024-11-30, збережений у теці з назвою msi під назвою, яку йому дає Bicep, — types.json.

Файл схеми Azure та його ліцензія

types.json для Microsoft.ManagedIdentity версії 2024-11-30 — це файл репозиторію Azure/bicep-types-az, авторське право Microsoft Corporation, поширюється за ліцензією MIT. Описи, які цитують наведені нижче чернетки, належать Microsoft, і на них поширюється повідомлення цієї ліцензії:

MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

Робочий простір — це тека, що містить .aggrega-config.yaml із ключем workspace, і тека msi із цим файлом:

.aggrega-config.yaml
msi/types.json

Перелік типів для чернетки

Файл схеми може містити більше одного типу ресурсу, а імпорт створює чернетки лише тих, які ви назвете. Перелічіть, що містить файл:

Terminal window
jq -r '.[] | select(."$type" == "ResourceType") | .name' msi/types.json
Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30
Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials@2024-11-30
Microsoft.ManagedIdentity/identities@2024-11-30

Потім назвіть потрібний тип у налаштуванні resource_types запису імпортера в .aggrega-config.yaml. Кожен робочий простір уже обслуговує імпортер, тож запис потрібен лише для того, щоб передати resource_types. Його uri називає імпортер і версію компілятора, яку друкує aggrega version; імпортер отримує свої налаштування через такий запис, як описано в розділі Який імпортер перетворює джерело на чернетки:

workspace: {}
default_registry: hub.aggrega.ai
plugins:
importer:
- uri: importer/arm-schema:<compiler version>
with:
settings:
resource_types:
- Microsoft.ManagedIdentity/userAssignedIdentities

Назви зіставляються точно для CloudFormation (AWS::SQS::Queue) і Terraform (aws_sqs_queue) та без урахування регістру для Azure, де назва може мати після @ версію API. Файлу, що містить рівно один тип, перелік не потрібен. Імпорт файлу з кількома типами без переліку зупиняється й називає їх:

halt: the sources hold 3 resource types and the resource_types setting names none: write the types to draft in it, one of Microsoft.ManagedIdentity/userAssignedIdentities, Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials, Microsoft.ManagedIdentity/identities

Перелічений тип, якого файл не містить, теж зупиняє імпорт, називаючи найближчі назви, які файл містить. Зупинка не створює чернеток, тож жоден файл не записується.

Запуск імпорту

Назвіть теку або файл:

Terminal window
aggrega import msi

У стандартний вивід він виводить перелік записаного:

wrote catalog/component/imported/security/microsoft-managedidentity-userassignedidentities/0.1.0/component.yaml
wrote catalog/recipe/arm/microsoft-managedidentity-userassignedidentities/0.1.0/recipe.yaml
wrote .aggrega-import.json

У стандартний потік помилок, де <workspace> позначає теку, у якій ви його запустили:

read as the arm-schema format, with drafted paths relative to <workspace>
mapped Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30 (Microsoft.ManagedIdentity/userAssignedIdentities) to imported/security/microsoft-managedidentity-userassignedidentities as a draft, NONE at 0.05

aggrega import розпізнає файл типів Bicep з назвою types.json, як їх називає Azure/bicep-types-az, а --format arm-schema називає формат для файлу з іншою назвою. --format — також спосіб імпортувати великий експорт, як-от повну схему провайдера Terraform, без того, щоб імпорт спершу його розпізнавав.

Рядок mapped означає, що тип ресурсу став окремою чернеткою, без жодного Component каталогу, близького до нього. Чернетки записуються в catalog/ — теку, яку робочий простір читає як каталог, тож вони розв’язуються під час наступної валідації та збірки без жодного налаштування. Запис .aggrega-import.json перелічує їх, тож aggrega import --sync може привести їх у відповідність до зміненої схеми, не перезаписуючи вашої правки.

Що кажуть чернетки

Component, component.yaml, розподіляє кожну властивість типу ресурсу до одного зі стовпів, а коментар поруч із кожним ключем називає правило, яке його розмістило:

  • Властивість для зворотного читання, яку встановлює хмара, а ви не можете, не є входом. Скаляр стає ключем provides, який може прочитати споживач.
  • Секрет створюється як посилання на те, звідки береться його значення, і ніколи як значення, як описано в розділі Секрети нижче.
  • Розміщення, тобто де живе ресурс, як-от location в Azure, потрапляє до infra — стовпа, який оператор задає для кожного середовища.
  • Ідентичність, тобто власна назва ресурсу, потрапляє до values — стовпа, який пише розробник.
  • Будь-яка інша обов’язкова властивість потрапляє до infra.
  • Кожна інша записувана властивість потрапляє до infra.overrides — відкритого відображення, яке зберігає власне написання вендором кожної назви.

Для цього типу ресурсу Component виглядає так:

apiVersion: aggrega.ai/v1beta1
kind: Component
metadata:
name: imported/security/microsoft-managedidentity-userassignedidentities
version: 0.1.0
description: "Draft Component of the resource type Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30, imported from a source in the arm-schema format."
labels:
component.aggrega.ai/type: resource
component.aggrega.ai/category: security
component.aggrega.ai/hosting: managed
spec:
schema:
values:
type: object
properties:
# identity: the resource's own name or identifier
# [vendor schema text] The resource name
name:
type: string
description: "[vendor schema text] The resource name"
required: true
additionalProperties: false
infra:
type: object
properties:
# placement: where the resource is deployed
# [vendor schema text] The geo-location where the resource lives
location:
type: string
description: "[vendor schema text] The geo-location where the resource lives"
required: true
# override: every writable property no other rule places, each under the vendor's own name
overrides:
type: object
description: "Writable settings of Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30, each under the vendor's own name, which the Recipe passes to the resource as written; its header lists the names it reads."
additionalProperties: true
additionalProperties: false
provides:
type: object
properties:
# read back: published under provides
# [vendor schema text] The resource id
id:
type: string
description: "[vendor schema text] The resource id"
# … client_id, principal_id and tenant_id, each read back the same way
additionalProperties: false

Кожен текст, який чернетка бере зі схеми вендора, починається з [vendor schema text], щоб ви могли його знайти й переписати власними словами, перш ніж Component залишить ваш робочий простір. Текст, який складає сам імпорт, маркера не має.

Recipe, recipe.yaml, реалізує Component на провайдері arm. Його коментар-заголовок перелічує кожен ключ, який він читає, з правилом і типом, а також те, чого він не читає:

spec:
# This Recipe realizes imported/security/microsoft-managedidentity-userassignedidentities with one resource of the type Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30. It reads the keys below, each with its type, its rule and the first sentence of the vendor's description; any other key under infra.overrides halts the build naming it.
# infra.location: string, required; placement: where the resource is deployed
# [… omitted: the first sentence of the vendor's description of the key above, marked as vendor schema text, as below each key]
# values.name: string, required; identity: the resource's own name or identifier
# [… omitted: the vendor's description of the key]
# infra.overrides.tags: object; override: writable, set under infra.overrides in the vendor's spelling
# [… omitted: the vendor's description of the key]
# infra.overrides.isolationScope: string; override: writable, set under infra.overrides in the vendor's spelling
# [… omitted: the vendor's description of the key, then a line saying template.yaml declares the resource under the symbolic name locals.symbol holds]
capability: arm
implements: imported/security/microsoft-managedidentity-userassignedidentities:0.1.0
locals:
# [… omitted: a comment saying what the symbolic name is made of]
symbol: "{{ capitalizedWords .context.instance_id }}"
provides:
# [… omitted: a comment saying each value is one whole ARM expression, evaluated when the template is deployed]
id: "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities'{{ range splitList \"/\" (toString (index .values \"name\")) }}, '{{ replace \"'\" \"''\" . }}'{{ end }})]"
client_id: "[reference('{{ .locals.symbol }}').clientId]"
# … principal_id and tenant_id the same way
assertions:
overrides_this_recipe_reads: |
# halts naming any key under infra.overrides the header does not list
artifacts:
template.yaml: |
# … the resource, written under the symbolic name locals.symbol holds

Recipe записує один ресурс — той, який називає тип, — і нічого більше: ні групи ресурсів, ні мережі, ні ідентичності, яку ви не оголошували. Кожне значення provides — це цілий вираз, який Azure обчислює під час розгортання шаблону й передає споживачеві як рядок, яким він є. Ключ infra.overrides, якого немає в заголовку, зупиняє збірку з його назвою, тож помилково написане налаштування виявляється ще до будь-якого розгортання.

Перегляньте обидва файли перед збіркою. Перенесення налаштування між стовпами — це правка Component і того, як його читає Recipe, а файли належать вам: ніщо, від чого залежить збірка, не зберігається деінде.

Використання чернеток в Aggregate і Release

Імпорт не створює чернеток Aggregate, Manifest і Release, тож рядки, які використовують створений Component, пишете ви. В Aggregate, aggregate.yaml, один компонент створеного типу з ідентичністю, яку містить стовп values:

apiVersion: aggrega.ai/v1beta1
kind: Aggregate
metadata:
name: identities
version: 1.0.0
spec:
components:
deploy-identity:
type: imported/security/microsoft-managedidentity-userassignedidentities:0.1.0
values:
name: deploy-identity

У Manifest, manifest.yaml, один рядок, який каже, який Recipe реалізує тип:

apiVersion: aggrega.ai/v1beta1
kind: Manifest
metadata:
name: identities
version: 1.0.0
spec:
mappings:
components:
type:
imported/security/microsoft-managedidentity-userassignedidentities:0.1.0: arm/microsoft-managedidentity-userassignedidentities:0.1.0

У Release, release.yaml, межа, до якої потрапляє компонент, і стовп infra, якого вимагає Recipe, — розміщення:

apiVersion: aggrega.ai/v1beta1
kind: Release
metadata:
name: identities
version: 1.0.0
environment: production
spec:
aggregate: ./aggregate.yaml
manifest: ./manifest.yaml
boundaries:
azure:
directory: azure
components:
deploy-identity:
infra:
location: westeurope

Перевірка та збирання

Terminal window
aggrega validate --release release.yaml
release dependency validation passed: release.yaml (schema-pillar + dependency pillars)

Отримайте те, від чого залежить Release, а потім зберіть:

Terminal window
aggrega pull --release release.yaml
aggrega build --release release.yaml
Pull complete: release.lock (entities=…, source_artifacts=…, external_inputs=…)
[… omitted: the build's elapsed time]
Build completed: 1 file written to <workspace>/dist

Збірка записує dist/azure/arm/arm-template.json — єдиний шаблон межі azure з одним ресурсом під символічною назвою, яку йому дає його екземпляр. Поряд із власними членами ресурсу збірка записує в metadata, які Aggregate, Release і Recipe його створили:

{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"languageVersion": "2.0",
"resources": {
"DeployIdentity": {
"apiVersion": "2024-11-30",
"location": "westeurope",
"metadata": {
"aggrega.ai/provenance": {
"aggrega.ai/aggregate-name": "identities",
"aggrega.ai/boundary-path": "azure",
"aggrega.ai/compiler-version": "<compiler version>",
"aggrega.ai/component-id": "deploy-identity",
"aggrega.ai/environment": "production",
"aggrega.ai/provider": "arm",
"aggrega.ai/provider-version": "<compiler version>",
"aggrega.ai/recipe-uri": "microsoft-managedidentity-userassignedidentities:0.1.0"
}
},
"name": "deploy-identity",
"type": "Microsoft.ManagedIdentity/userAssignedIdentities"
}
}
}

Шаблон — це те, що ви передаєте Azure; провайдер arm описує команди, які розгортають його в області групи ресурсів. Тип ресурсу, який можна записати лише в області підписки або групи керування, створюється як фрагмент для цієї області, а заголовок його Recipe називає анотацію межі, яку задає Release, як описано в розділах Розгортання в області підписки і Розгортання в області групи керування. Тип, який можна записати лише в області тенанта або лише як розширення іншого ресурсу, відхиляється за назвою.

Секрети

Значення секретної властивості ніколи не записується в чернетку, і для неї не створюється значення за замовчуванням. Як воно потрапляє до ресурсу, залежить від провайдера:

  • Azure: параметр шаблону верхнього рівня securestring, названий за екземпляром і властивістю, який ви задаєте під час розгортання. Секрет, який вендор позначає як необов’язковий, є обов’язковим параметром.
  • CloudFormation: запис шаблону Parameters, позначений NoEcho, названий так само. Секрет, який вендор позначає необов’язковим, стає обов’язковим параметром.
  • Terraform: слот Feature у Component і змінна модуля, позначена sensitive: true; значення надходить через секрет, який Release приєднує до слота.

Секретом стає лише властивість на верхньому рівні ресурсу — в Azure ключ кореня або член properties. Чутливий член нижче неї, наприклад adminPassword усередині osProfile в Azure або password усередині блока Terraform, не створюється як секрет: сутність Release задає його як звичайне значення всередині ключа, під яким створюється його батьківський елемент, а імпорт попереджає про кожен такий член під constraint-dropped, називаючи його шлях і цей ключ.

Властивість CloudFormation читається як секрет, коли її назва містить слово про облікові дані — password, secret, token, credential, private key, API key або passphrase — і не закінчується на Arn, Id, Name чи Ref. Таке читання — домовленість чернетки, а заголовок Recipe позначає кожну властивість, яку він прочитав як секрет, тож ви підтверджуєте їх під час перегляду.

Той самий імпорт для CloudFormation і Terraform

Кроки ті самі; відрізняються лише експорт і форма Recipe. Два наведені нижче випадки створено із синтетичних схем, текст вендора з яких у подальшому викладі пропущено.

CloudFormation

Terminal window
aws cloudformation describe-type --type RESOURCE --type-name AWS::Example::Ledger > ledger.json
aggrega import ledger.json

Імпорт записує Component і Recipe та одне попередження для кожного обмеження вендора, яке він не може перенести:

wrote catalog/component/imported/component/aws-example-ledger/0.1.0/component.yaml
wrote catalog/recipe/cloudformation/aws-example-ledger/0.1.0/recipe.yaml
wrote .aggrega-import.json
read as the cloudformation-schema format, with drafted paths relative to <workspace>
warn: the property "LedgerName" does not carry the vendor schema's pattern "…": the catalog reads a pattern as an RE2 regular expression, which refuses it: …
warn: the property "Rules[].Children[]" does not carry the vendor schema's shape below it: the vendor schema's definitions refer back to themselves there, so it is drafted as an open object
mapped AWS::Example::Ledger (AWS::Example::Ledger) to imported/component/aws-example-ledger as a draft, NONE at 0.0167

template.yaml Recipe оголошує ресурс під логічним ідентифікатором, який йому дає екземпляр, із секретом як параметром NoEcho і кожним ключем provides, записаним як !Ref або !GetAtt, повторений під provides, щоб провайдер cloudformation спроєктував його у Outputs стека:

artifacts:
template.yaml: |
Parameters:
{{ .locals.logical_id }}MasterPassword:
Type: String
NoEcho: true
Resources:
{{ .locals.logical_id }}:
Type: AWS::Example::Ledger
Properties:
# … one line for each key the header lists
MasterPassword: !Ref {{ .locals.logical_id }}MasterPassword
provides:
arn: !GetAtt {{ .locals.logical_id }}.Arn

Terraform

Terminal window
terraform init && terraform providers schema -json > schema.json
aggrega import schema.json
wrote catalog/component/imported/component/aws-example-ledger/0.1.0/component.yaml
wrote catalog/recipe/terraform/aws-example-ledger/0.1.0/recipe.yaml
wrote catalog/recipe/terraform/aws-example-ledger/0.1.0/module/main.tf.json
wrote .aggrega-import.json

Експорт Terraform називає провайдерів, яких вимагає конфігурація, але не їхні версії, тож імпорт попереджає:

warn: no version of the provider hashicorp/aws is known, so the module drafted for aws_example_ledger requires it without a version constraint: set terraform.required_providers.aws.version in the module/main.tf.json beside the Recipe, then run aggrega pin on the Recipe

Чернетка Terraform — це Recipe з модулем поряд. module/main.tf.json оголошує по одній змінній для кожного входу, один ресурс, this, із кожним аргументом, прочитаним зі своєї змінної, і провайдера, якого називає експорт. spec.source Recipe вказує на модуль, а його valuesMapping заповнює кожну змінну зі стовпів Component, записуючи необов’язковий вхід лише там, де його задає Release. Закріпіть модуль перед першим pull, щоб lock записав його дайджест:

Terminal window
aggrega pin catalog/recipe/terraform/aws-example-ledger/0.1.0/recipe.yaml
Pinned Recipe "aws-example-ledger": wrote <workspace>/catalog/recipe/terraform/aws-example-ledger/0.1.0/entity.lock (remote source pins: 0, imported file pins: 0, local source file pins: 1). Commit it beside the entity

Незакріплений Recipe зупиняє pull, називаючи aggrega pin. Закріплюйте знову після кожної правки модуля.

Рядки Aggregate, Manifest і Release — ті самі, що й у випадку Azure, зі створеними назвами та власним infra провайдера: Release для Terraform називає ключі розміщення провайдера, як-от region, де їх оголошує Component.

Component, який у каталозі вже є

Коли каталог містить Component для сервісу, а для вашого провайдера бракує лише Recipe, назвіть цей Component у налаштуванні. Тоді імпорт створює чернетку лише Recipe, записаного відносно стовпів Component. Кожен запис resource_types — це назва типу або об’єкт із типом і Component:

plugins:
importer:
# The entry passes resource_types; the importer is served without it.
- uri: importer/arm-schema:<compiler version>
with:
settings:
resource_types:
- type: Microsoft.ManagedIdentity/userAssignedIdentities
component: acme/security/identity

Recipe отримує назву identity-microsoft-managedidentity-userassignedidentities за Component, тож він ніколи не перебирає назву Recipe, який каталог уже містить. Component каталогу, що оголошує ключ values з назвою, як у властивості типу, читає цю властивість із values; властивість, яку вимагає вендор, а Component для неї ключа не має, читається з infra.overrides із твердженням, яке зупиняє збірку, доки Release її не задасть. Кожен ключ, який надає Component і який збігається за назвою з атрибутом для зворотного читання, записується. Для кожного іншого чернетка записує шаблон, який завершується помилкою з назвою ключа, тож збірка зупиняється, доки ви його не зіставите, а імпорт попереджає:

warn: the Component acme/security/identity provides principal_id, and no attribute Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30 reads back carries its name, so the drafted Recipe's provides.principal_id halts the build until it is mapped: map it to an attribute Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30 reads back, one of id, properties.clientId, properties.principalId, properties.tenantId

Azure вкладає цей атрибут під properties, тож рядок, який слід написати, — той, що містить повна чернетка типу:

provides:
principal_id: "[reference('{{ .locals.symbol }}').principalId]"

Коли цей рядок записано, Release називає Component у своєму Aggregate і Recipe у своєму Manifest, як вище, задає розміщення під infra.overrides.location, проходить валідацію і збирається в той самий шаблон.

Назва, для якої каталог не містить Component, створюється як новий Component під цією назвою, і імпорт попереджає, щоб помилково написану назву Component не сприйняли за нову.

Що далі

  • Базові імпортери описують, що читає кожен імпортер, як він вибирає між кількома типами та між кількома провайдерами, поділ повністю, що створює кожна ціль і які діагностики повідомляють усі три.
  • Провайдер arm описує шаблон, у який зливається чернетка Azure, і області, у яких він розгортається.
  • aggrega import — повний довідник команди.