Metadata-Version: 2.4
Name: yc2terraform
Version: 0.0.3
Summary: Generate Terraform manifests (HCL) for existing Yandex Cloud resources
Author-email: Aleksei Marusich <aleksei.marusich@rocshers.com>
License: MIT
Project-URL: Homepage, https://projects.rocshers.com/open-source/yc2terraform
Project-URL: Repository, https://gitlab.com/rocshers/python/yc2terraform
Keywords: yandex-cloud,terraform,hcl,import,infrastructure-as-code
Classifier: Environment :: Console
Classifier: Topic :: System :: Systems Administration
Requires-Python: >=3.14
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.28.1
Requires-Dist: rich>=15.0.0
Requires-Dist: typer>=0.29.1

# yc2terraform

[![PyPI](https://img.shields.io/pypi/v/yc2terraform)](https://pypi.org/project/yc2terraform/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/yc2terraform)](https://pypi.org/project/yc2terraform/)

[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=rocshers_yc2terraform&metric=coverage)](https://sonarcloud.io/summary/new_code?id=rocshers_yc2terraform)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=rocshers_yc2terraform&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=rocshers_yc2terraform)

[![Downloads](https://pypi.rocshers.com/badges/svg/packages/yc2terraform/downloads/total)](https://clickpy.clickhouse.com/dashboard/yc2terraform)
[![GitLab stars](https://img.shields.io/gitlab/stars/rocshers/python/yc2terraform)](https://gitlab.com/rocshers/python/yc2terraform)
[![GitLab last commit](https://img.shields.io/gitlab/last-commit/rocshers/python/yc2terraform)](https://gitlab.com/rocshers/python/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](https://github.com/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](#differences-from-yc-terraformer).

## Why

- **Move to Terraform**: bring resources created in the console or with `yc` under 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 the `yc` naming, as yc-terraformer did. Any `yandex_*` type is supported. If you leave out the ID, it is looked up by name with `yc`.
- `--recursive` also 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 folder` runs `yc <service> <type> list` for 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. `cloud` does the same for every folder of a cloud. Both replace the `yc ... list | jq | xargs` loops.
- **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` / `*_ids` values go to `yc2terraform.auto.tfvars.json`. Sensitive values such as passwords go to a separate `yc2terraform.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.
- **Types the provider cannot import** (`yandex_api_gateway`) are built from the REST API instead, spec included. They can't be added to state, so `--with-state` and `--import-blocks` skip them.
- 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

```bash
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](https://yandex.cloud/en/docs/tutorials/infrastructure-management/terraform-quickstart#configure-provider)). 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:

1. `$YC_TOKEN`: an IAM token, or an OAuth token (exchanged for an IAM token automatically).
2. `yc iam create-token`, if the `yc` CLI 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`; the default cloud is `$YC_CLOUD_ID`, then `yc config get cloud-id`. An ID passed on the command line always wins.

```bash
export YC_TOKEN=$(yc iam create-token)
```

A plain `import` without `--recursive` uses only the provider. For that, any [provider auth env var](https://yandex.cloud/en/docs/terraform/quickstart#configure-provider) works too, e.g. `YC_SERVICE_ACCOUNT_KEY_FILE`.

## Quick start

```bash
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

# Find IDs: clouds, folders of a cloud ($YC_CLOUD_ID or the yc profile cloud), as ID<TAB>NAME
yc2terraform clouds [--organization-id bpf...]
yc2terraform folders [b1g9876543210abcdefg]

# 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):

```bash
export YC_FOLDER_ID=b1g0123456789abcdefg     # or: yc config set folder-id ...

uvx yc2terraform folder \
  --with-state \
  --import-ids \
  --import-metadata
```

What happens:

1. `yc <service> <type> list --folder-id $YC_FOLDER_ID --format json` runs for every type, up to 8 at a time. If `yc` fails for a type, the REST API is tried. If both fail (no permission, service not enabled), the type is skipped with a warning.
2. Linked resources are added: disks, DB users and databases, Kafka topics, ALB virtual hosts, node groups, and so on.
3. 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.
4. Everything is imported in parallel, written as one file per resource, then imported into the state of the current directory (`--with-state`).

Useful variations:

```bash
# 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.

```bash
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:

```bash
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:

```bash
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

```bash
# 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`.

```bash
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

```bash
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.

```bash
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`:

```bash
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)

```bash
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

```bash
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

```bash
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
```

```hcl
# 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

1. **Discover.** `folder`/`cloud` list resources with `yc` (falling back to the REST API). With `--recursive` (on by default for `folder`), the REST API is used to find linked resources. Requests run concurrently, and each resource is visited only once.
2. **Import.** In a temporary directory with a bare `provider "yandex" {}`, each resource gets an empty stub and is imported with `terraform import -state=<own file>`. Imports run in parallel.
3. **Convert.** The state attributes are filtered through the provider schema (`terraform providers schema -json`) and the cleanup rules in `registry.py`. Then IDs become references or variables, and the result is rendered as HCL and run through `terraform fmt`.
4. **Verify.** You run `terraform plan`. If it wants changes, fix the manifest, and please [open an issue](https://gitlab.com/rocshers/python/yc2terraform/-/issues) with the resource type and the plan diff.

## Safety

- Everything is read-only until you `apply`. Without `--with-state` and `--import-blocks`, your state is never changed.
- Be careful with `--with-state`, `--import-blocks` and `--import-ids`. Once the manifests are bound to live resources, a careless edit followed by `apply` changes production. If you only needed a copy or a repro, remove the files and run `terraform state rm` afterwards.
- `*.secrets.auto.tfvars.json` contains 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

```bash
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>
