pulumi-terraform-to-pulumi

от pulumi

Миграция проектов Terraform/OpenTofu в Pulumi, включая перевод исходного кода HCL и/или импорт состояния Terraform в стек Pulumi. Используйте, когда пользователь…

npx skills add https://github.com/pulumi/agent-skills --skill pulumi-terraform-to-pulumi

Migrating from Terraform to Pulumi

Critical constraints — read before acting:

  • Do NOT run pulumi convert — use the terraform-migrate plugin instead, which preserves state mapping.
  • Do NOT run pulumi package add terraform-module — this is for a different workflow.
  • Do NOT create the Pulumi project under /workspace — create it inside the checked-out repo.
  • Replace ${terraform_dir} and ${pulumi_dir} below with the actual paths confirmed with the user.

First establish scope and plan the migration by working out with the user:

  • where the Terraform sources are (${terraform_dir})
  • where the migrated Pulumi project lives (${pulumi_dir})
  • what is the target Pulumi language (such as TypeScript, Python, YAML)
  • whether migration aims to setup Pulumi stack states, or only translate source code

Confirm the plan with the user before proceeding.

Create a new Pulumi project in ${pulumi_dir} in the chosen language. Edit sources to be empty and not declare any resources. Ensure a Pulumi stack exists.

You must run pulumi_up tool before proceeding to ensure initial stack state is written.

If no local .tfstate file exists in ${terraform_dir}, the state may be in a remote backend (S3, Pulumi Cloud, Terraform Cloud, etc.). Pull it before proceeding:

cd ${terraform_dir} && terraform state pull > terraform.tfstate

This works for all backends, including Pulumi Cloud. If terraform is not available, try tofu state pull instead.

Now produce a draft Pulumi state translation:

pulumi plugin run terraform-migrate -- stack \
    --from ${terraform_dir} \
    --to ${pulumi_dir} \
    --out /tmp/pulumi-state.json \
    --plugins /tmp/required-providers.json

Do NOT install the plugin as it will auto-install as needed.

Sometimes terraform-migrate plugin fails because tofu refresh is not authorized. DO NOT skip this step. Work with the user to find or build a Pulumi ESC environment that provides the necessary credentials so the command can succeed. If setting up an ESC environment is not feasible, inform the user that the migration cannot proceed automatically.

Read the generated /tmp/required-providers.json and install all these Pulumi providers into the new project, respecting the suggested versions even if they downgrade an already installed provider. The file will contain records such as [{"name":"aws","version":"7.12.0"}].

Install providers as project dependencies using the language-specific package manager (NOT pulumi plugin install, which only downloads plugins without adding dependencies):

# TypeScript/JavaScript
npm install @pulumi/aws@7.12.0

# Python
pip install pulumi_aws==7.12.0

# Go
go get github.com/pulumi/pulumi-aws/sdk/v7@v7.12.0

# C#
dotnet add package Pulumi.Aws --version 7.12.0

Import the translated state draft (/tmp/pulumi-state.json) into the Pulumi stack:

pulumi stack import --file /tmp/pulumi-state.json

Translate source code to match both the Terraform source and the translated state. Aim for exact match. You can consult the state draft /tmp/pulumi-state.json for Pulumi resource types and names to use.

Iterate on fixing the source code until pulumi_preview tool confirms that there are no changes to make and the diff is empty or almost empty. Provider diffs or diffs on tags may be OK.

Offer the user to link an ESC environment to the stack so that each Pulumi stack can seamlessly have access to the provider credentials it needs.

When all looks good, create a Pull Request with the migrated source code.

Больше skills от pulumi

package-usage
pulumi
Отслеживание, какие стеки в организации Pulumi используют определённый пакет и на каких версиях. Используется для межстековых аудитов, выявления устаревших или неподдерживаемых…
official
pulumi-automation-api
pulumi
Программная оркестрация операций с инфраструктурой Pulumi для нескольких стеков и приложений. Поддерживает архитектуры как с локальным исходным кодом (существующие проекты Pulumi), так и со встроенным исходным кодом (встраиваемые программы), что обеспечивает гибкие шаблоны развертывания — от простых до сложных сценариев с несколькими стеками. Обрабатывает оркестрацию нескольких стеков с последовательностью зависимостей, параллельными независимыми развертываниями и передачей выходных данных между стеками для координированного предоставления инфраструктуры. Обеспечивает программное...
official
pulumi-best-practices
pulumi
Всесторонние лучшие практики написания надежного, поддерживаемого инфраструктурного кода Pulumi. Избегайте создания ресурсов внутри колбэков apply(); передавайте объекты Output напрямую в качестве входных данных для сохранения отслеживания зависимостей и видимости в предварительном просмотре. Используйте классы ComponentResource для группировки связанных ресурсов в переиспользуемые логические единицы с правильной иерархией родитель-потомок через parent: this. Шифруйте секреты с самого начала с помощью флага --secret или config.requireSecret() для предотвращения утечки учетных данных в файлах состояния...
official
pulumi-component
pulumi
Многоразовые компоненты инфраструктуры с поддержкой нескольких языков, разумными значениями по умолчанию и шаблонами композиции. Требует четыре основных элемента: расширение ComponentResource, принятие стандартных параметров, установка parent: this для всех дочерних элементов и вызов registerOutputs() в конце конструктора. Интерфейсы Args должны использовать обёртки Input<T>, избегать объединённых типов и функций, а также сохранять плоскую структуру для поддержки генерации SDK на нескольких языках. Предоставлять только основные выходные данные как публичные свойства; скрывать...
official
pulumi-debug-failed-operation
pulumi
Отладка обновления или предварительного просмотра Pulumi, завершившегося сбоем: прочитайте зафиксированную Pulumi ошибку, найдите её причину и исправьте. Загружайте этот навык, когда пользователь просит…
official
pulumi-esc
pulumi
Централизованное управление секретами, конфигурацией и динамическими учетными данными для инфраструктуры и приложений Pulumi. Поддерживает композицию окружений через импорт и наслоение с зарезервированными ключами для environmentVariables, pulumiConfig и files. Генерирует краткосрочные учетные данные через OIDC для AWS, Azure и GCP; интегрируется с AWS Secrets Manager, Azure Key Vault, HashiCorp Vault и 1Password. Основные команды CLI включают pulumi env init, pulumi env edit, pulumi env open (раскрывает...
official
pulumi-neo-handoff
pulumi
Передать текущий поток новому заданию Pulumi Neo в виде односторонней передачи. Используйте, когда пользователь явно просит передать, отправить, перевести или продолжить текущий…
official
pulumi-overview
pulumi
Используйте этот навык для любой задачи, которая создает, изменяет, проверяет или уничтожает облачную инфраструктуру или конфигурацию SaaS, от разовых операций CLI до полного…
official