yc2terraform
Generate Terraform manifests (HCL) for existing Yandex Cloud resources: one resource, a resource and everything it is linked to, a whole folder or a whole cloud.
It started as a rewrite of yandex-cloud-examples/yc-terraformer, a single-file script. The use cases and flags are the same. The changes are listed in Differences from yc-terraformer.
Why
- Move to Terraform: bring resources created in the console or with
ycunder Terraform management. - Back up your configuration: keep manifests of production resources so you can recreate them after an accidental deletion or an outage.
- Clone an environment: deploy the same configuration in another zone, folder or cloud (staging, load tests, migration during a zone outage).
- Reproduce problems: support engineers get the exact configuration of a customer's resource and can stand up a copy to debug it.
- Learn Terraform: change a setting in the console, export the resource, and see which Terraform arguments you need.
- Investigate a surprising
terraform plan: export the live resource and compare it with your code.
Features
import SERVICE TYPE NAME [ID]uses theycnaming, as yc-terraformer did. Anyyandex_*type is supported. If you leave out the ID, it is looked up by name withyc.--recursivealso exports linked resources: VM disks; DB users and databases; Kafka users, topics and connectors; ALB routers, virtual hosts, backend and target groups; NLB target groups; Data Transfer endpoints; VPC subnets, security groups and route tables; Kubernetes node groups.- Full folder dump in one command.
yc2terraform folderrunsyc <service> <type> listfor 55 resource types (IAM, VPC, Compute, Managed Kubernetes, every managed database, ALB/NLB, DNS, KMS, Certificate Manager, Lockbox, Object Storage, Serverless, Logging, Data Transfer, Data Proc, CDN, IoT) and exports everything it finds, with linked resources.clouddoes the same for every folder of a cloud. Both replace theyc ... list | jq | xargsloops. - References instead of IDs. When the referenced resource is exported too, the ID is written as a reference:
network_id = yandex_vpc_network.main.id. References that would form a cycle (two security groups that cite each other) stay as IDs. - Variables for everything else. Other
*_id/*_idsvalues go toyc2terraform.auto.tfvars.json. Sensitive values such as passwords go to a separateyc2terraform.secrets.auto.tfvars.json, so the manifests can be committed. - Uses the provider schema. Computed-only and deprecated attributes are dropped, and nested blocks are told apart from map attributes correctly. A small set of hand-written rules (inherited from yc-terraformer) covers the remaining quirks.
- Does not touch your state. Imports run in a temporary workspace with one state file per resource, in parallel (
--parallel). Your project's state changes only with--with-state. - Safe to run again. A second run into the same directory reuses the same resource names, overwrites the files it wrote before, merges variables, and references resources exported earlier.
- Output is passed through
terraform fmt. Cloud-init and other multi-line values are written as heredocs. - Works with Terraform >= 1.5 or OpenTofu (
--terraform tofu).
Install
uv tool install yc2terraform # or: pipx install yc2terraform
# one-off: uvx yc2terraform --help
You also need terraform in PATH. In Russia, set up the Yandex provider mirror in ~/.terraformrc (guide). The provider is downloaded once and cached in ~/.cache/yc2terraform/plugins.
Authentication
Read-only access is enough: give a service account (or yourself) the viewer role on the cloud or folder.
The tool needs a token for two things: the Terraform provider and, for --recursive / folder / cloud, the YC REST API. It looks for one in this order:
$YC_TOKEN: an IAM token, or an OAuth token (exchanged for an IAM token automatically).yc iam create-token, if theycCLI is installed and configured.
The yc CLI is optional but recommended. When it is installed, folder and cloud list resources through it, which covers every type yc knows. Without it, they fall back to the REST API, which covers fewer types (see yc2terraform types). yc uses your active profile; set YC_PROFILE to pick another one. The default folder is $YC_FOLDER_ID, then yc config get folder-id.
export YC_TOKEN=$(yc iam create-token)
A plain import without --recursive uses only the provider. For that, any provider auth env var works too, e.g. YC_SERVICE_ACCOUNT_KEY_FILE.
Quick start
mkdir infra && cd infra
# One VM with its disks
yc2terraform import -r compute instance web-1 fhm0123456789abcdefg
# A PostgreSQL cluster with its users and databases
yc2terraform import -r managed-postgresql cluster pg-prod c9q0123456789abcdefg
# An ALB with its routers, virtual hosts, backend and target groups
yc2terraform import -r application-load-balancer load-balancer alb-main ds70123456789abcdefg
# A bucket (the import ID is the bucket name)
yc2terraform import storage bucket my-bucket
# Look the ID up by name (needs yc)
yc2terraform import -r compute instance web-1
# Everything in a folder, or only some types
yc2terraform folder # $YC_FOLDER_ID or the yc profile folder
yc2terraform folder b1g0123456789abcdefg -o prod/
yc2terraform folder b1g0123456789abcdefg --only compute.instance --only vpc.network
# Every folder in a cloud, one sub-directory each
yc2terraform cloud b1g9876543210abcdefg -o backup/
terraform init && terraform plan # expect: No changes
SERVICE and TYPE are named as in yc: iam service-account, vpc security-group, managed-kubernetes node-group, managed-kafka topic, and so on. You can also pass a Terraform type directly: yc2terraform import yandex_compute_instance - web-1 fhm... (the second argument is then ignored). yc2terraform types lists the types that support recursion and folder export.
Examples
All examples use uvx, so nothing needs to be installed except uv and terraform. yc is recommended.
Full folder dump in one command
This replaces a hand-written while read service resource; do yc $service $resource list ...; done loop over every resource type. The type list is built in (yc2terraform types prints it):
export YC_FOLDER_ID=b1g0123456789abcdefg # or: yc config set folder-id ...
uvx yc2terraform folder \
--with-state \
--import-ids \
--import-metadata
What happens:
yc <service> <type> list --folder-id $YC_FOLDER_ID --format jsonruns for every type, up to 8 at a time. Ifycfails for a type, the REST API is tried. If both fail (no permission, service not enabled), the type is skipped with a warning.- Linked resources are added: disks, DB users and databases, Kafka topics, ALB virtual hosts, node groups, and so on.
- Resources that were created automatically are skipped: VMs and disks of instance groups and Kubernetes node groups, and the default security group of each network.
- Everything is imported in parallel, written as one file per resource, then imported into the state of the current directory (
--with-state).
Useful variations:
# Into a separate directory, without touching any state
uvx yc2terraform folder -o "dump-$(date +%F)/"
# Only some types, or everything except some
uvx yc2terraform folder --only vpc.network --only "compute instance" --only managed-postgresql.cluster
uvx yc2terraform folder --skip storage.bucket --skip "serverless function"
# Another folder or yc profile
YC_PROFILE=prod uvx yc2terraform folder b1g9876543210abcdefg -o prod/
# Every folder of a cloud: backup/<folder-name>/
uvx yc2terraform cloud "$CLOUD_ID" -o backup/ --import-ids
Every VM in a folder (the yc-terraformer way)
The pipeline from yc-terraformer works as before: xargs adds NAME ID to the end of each command.
yc compute instance list \
--folder-id "$FOLDER_ID" \
--format json |
jq -r '.[] | "\(.name) \(.id)"' |
xargs -n 2 uvx yc2terraform import \
--with-state \
--import-ids \
--import-metadata \
--recursive compute instance
The same with the built-in command. It runs once, imports in parallel, writes references between the VMs and their disks, and skips VMs owned by instance groups or Kubernetes node groups. Recursion is on by default here:
uvx yc2terraform folder "$FOLDER_ID" \
--only compute.instance \
--with-state \
--import-ids \
--import-metadata
Other resource types with yc + xargs
Any yc <service> <type> list works the same way:
yc managed-postgresql cluster list --folder-id "$FOLDER_ID" --format json |
jq -r '.[] | "\(.name) \(.id)"' |
xargs -n 2 uvx yc2terraform import -r -o pg/ managed-postgresql cluster
yc vpc security-group list --folder-id "$FOLDER_ID" --format json |
jq -r '.[] | "\(.name) \(.id)"' |
xargs -n 2 uvx yc2terraform import -o vpc/ vpc security-group
Every folder of a cloud
# Built in: one sub-directory per folder
uvx yc2terraform cloud "$CLOUD_ID" -o backup/
# Or with yc, when you need your own folder filter
yc resource-manager folder list --cloud-id "$CLOUD_ID" --format json |
jq -r '.[] | select(.name | startswith("prod-")) | "\(.id) \(.name)"' |
while read -r id name; do
uvx yc2terraform folder "$id" -o "backup/$name"
done
Configuration backup (daily, e.g. from cron or CI)
The manifests keep only configuration and contain no secrets, so they can be committed. Add *.secrets.auto.tfvars.json to .gitignore.
uvx yc2terraform folder "$FOLDER_ID" -o infra-backup/ --import-ids
cd infra-backup && git add -A && git commit -m "Snapshot $(date +%F)"
Clone an environment into another folder
uvx yc2terraform folder "$PROD_FOLDER_ID" -o staging/ --skip storage.bucket
cd staging
# edit yc2terraform.auto.tfvars.json: folder_id -> staging folder, zones, subnet IDs, ...
# rename anything that has to be globally unique (buckets, DNS zones, registries)
terraform init && terraform plan
Without --import-ids, folder and other IDs are written as variables, and links between exported resources become references. Usually changing folder_id is enough.
Adopt existing resources into Terraform
Using import blocks: terraform plan shows what will be imported, and apply writes it to state.
uvx yc2terraform import -r --import-blocks managed-kubernetes cluster k8s-prod "$CLUSTER_ID"
terraform init && terraform plan # expect: N to import, 0 to add, 0 to change, 0 to destroy
terraform apply
Or import right away with --with-state:
uvx yc2terraform import -r --with-state application-load-balancer load-balancer alb-main "$ALB_ID"
terraform plan # expect: No changes
Reproduce a customer's resource (support)
uvx yc2terraform import -r -o repro/ managed-kafka cluster kafka-1 "$CLUSTER_ID"
cd repro && terraform init && terraform apply # creates a copy in your folder
# when done:
terraform destroy && cd .. && rm -rf repro
Learn which Terraform arguments a console setting maps to
uvx yc2terraform import -o before/ compute instance web-1 "$VM_ID"
# change the setting in the console
uvx yc2terraform import -o after/ compute instance web-1 "$VM_ID"
diff -ru before/ after/
OpenTofu, a pinned version, debugging
uvx yc2terraform import --terraform tofu vpc network main "$NETWORK_ID"
uvx yc2terraform@1.2.3 folder "$FOLDER_ID" # pin any published version
uvx yc2terraform import --debug -r compute instance web-1 "$VM_ID"
Output
infra/
├── provider.tf # written only if no provider "yandex" exists yet
├── yandex_compute_instance.web-1.tf # one file per resource
├── yandex_compute_disk.web-1-boot.tf
├── yc2terraform.variables.tf # variable declarations (regenerated)
├── yc2terraform.auto.tfvars.json # IDs: folder_id, subnet_id, ...
└── yc2terraform.secrets.auto.tfvars.json # sensitive values: add this file to .gitignore
# yc2terraform: yandex_compute_instance fhm0123456789abcdefg
resource "yandex_compute_instance" "web-1" {
folder_id = var.folder_id
name = "web-1"
platform_id = "standard-v3"
zone = "ru-central1-a"
boot_disk {
disk_id = yandex_compute_disk.web-1-boot.id
}
network_interface {
subnet_id = var.subnet_id
security_group_ids = var.security_group_ids
}
resources {
cores = 2
memory = 4
}
}
The header comment records the import ID. Later runs use it to keep the same address for the same cloud resource.
Options
| Option | Meaning |
|---|---|
-o, --output DIR |
Where to write files (default: current directory). |
-r, --recursive |
import: also export linked resources. On by default for folder/cloud; turn off with --no-recursive. |
--import-ids |
Keep literal IDs in manifests instead of moving them to variables. References to exported resources are still used. |
--import-metadata |
Keep metadata on instances and instance group templates. It is dropped by default because it holds cloud-init and SSH keys. |
--with-state |
After writing the files, run terraform import into the output directory's state. Resources already in state are skipped. |
--import-blocks |
Add import { to = ..., id = ... } blocks (Terraform >= 1.5). terraform plan then shows the imports, and apply adopts them. |
--only TYPE, --skip TYPE |
folder/cloud: limit the exported types (compute.instance, "compute instance" or yandex_compute_instance). Repeatable. |
--folder-id ID |
import: folder for the name lookup when ID is omitted. |
-p, --parallel N |
Number of concurrent terraform import processes (default 4). |
--terraform BIN |
Terraform binary, e.g. tofu. |
--debug |
Verbose logs, including every API call and terraform command. |
The exit code is 0 on success, 1 if any resource failed (the others are still written), and 2 on setup errors (no terraform, no token).
How it works
- Discover.
folder/cloudlist resources withyc(falling back to the REST API). With--recursive(on by default forfolder), the REST API is used to find linked resources. Requests run concurrently, and each resource is visited only once. - Import. In a temporary directory with a bare
provider "yandex" {}, each resource gets an empty stub and is imported withterraform import -state=<own file>. Imports run in parallel. - Convert. The state attributes are filtered through the provider schema (
terraform providers schema -json) and the cleanup rules inregistry.py. Then IDs become references or variables, and the result is rendered as HCL and run throughterraform fmt. - Verify. You run
terraform plan. If it wants changes, fix the manifest, and please open an issue with the resource type and the plan diff.
Safety
- Everything is read-only until you
apply. Without--with-stateand--import-blocks, your state is never changed. - Be careful with
--with-state,--import-blocksand--import-ids. Once the manifests are bound to live resources, a careless edit followed byapplychanges production. If you only needed a copy or a repro, remove the files and runterraform state rmafterwards. *.secrets.auto.tfvars.jsoncontains plaintext secrets (DB user passwords and other sensitive provider attributes). Keep it out of git.
Differences from yc-terraformer
| yc-terraformer | yc2terraform |
|---|---|
yc-terraformer.py [flags] service type name id |
yc2terraform import [flags] service type name [id] |
| Runs in your Terraform project and writes stubs and state there | Isolated temporary workspace; your state changes only with --with-state |
Imports run one at a time, with sleep(1) |
Concurrent API discovery and parallel imports |
| Hand-written list of fields to delete | Provider schema plus a small set of rules |
*_id → var.*, and you write variables.tf / terraform.tfvars yourself |
References between exported resources; variables and values generated and merged |
yc list | jq | xargs loops for bulk export |
folder (55 types, via yc or REST) and cloud commands |
| ID is required | ID optional: looked up by name with yc |
Resource name <name>_<root id>, can be invalid HCL |
Names cleaned up and made unique, stable across runs |
| ALB routes to backend groups were never followed (camelCase/snake_case mix-up) | Fixed; TLS/SNI handlers are followed too |
Development
make test # pytest; the end-to-end test uses tests/fake_terraform.py, so no cloud or terraform is needed
make format # ruff + mypy
Layout: cli.py (Typer commands), export.py (the pipeline), discovery.py (recursive and folder discovery), api.py (async YC REST client), yc.py (yc CLI wrapper), terraform.py (subprocess wrapper and workspace), hcl.py (rendering, variables), registry.py (type mapping, API paths, cleanup rules).
To add a type to the folder dump, add its yc pair to registry.FOLDER_KINDS. If its Terraform name doesn't follow yandex_<service>_<type>, add it to registry.TYPE_OVERRIDE. To support recursion for a type, add its REST collection to registry.API and an expander to discovery.EXPANDERS.
Contribute
Issue Tracker: https://gitlab.com/rocshers/python/yc2terraform/-/issues Source Code: https://gitlab.com/rocshers/python/yc2terraform
Metadata
Release files for yc2terraform 0.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| yc2terraform-0.0.2.tar.gz | 38.5 kB | Without provenance | Details for yc2terraform-0.0.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| yc2terraform-0.0.2-py3-none-any.whl | Python 3 | none | any | Details for yc2terraform-0.0.2-py3-none-any.whl |
Total release size: 73.4 kB
Release files / yc2terraform-0.0.2.tar.gz
| Download URL | yc2terraform-0.0.2.tar.gz |
|---|---|
| Size | 38.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4d10d3a6a1a798aa0d3e49b90c735585df0b41afefd57dc86f533045f9480710
|
|
BLAKE2b-256 checksum How to use checksums |
2e5a32ddc7b9841ae9fbdcb78bbaf44ac12129c8b77850c60ca5aeee7cd3bed7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / yc2terraform-0.0.2-py3-none-any.whl
| Download URL | yc2terraform-0.0.2-py3-none-any.whl |
|---|---|
| Size | 34.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4e6b5060c65a6c3e3b21875298fad0337eaccc2fdd40d352567f6ab2650f67ce
|
|
BLAKE2b-256 checksum How to use checksums |
7253a4086af9c04879d911000174cae8151478f0de8563963e189f0a9c6b47fc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for yc2terraform 0.0.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.