# Automating BTP with Terraform: the account model as reviewed code

> Manage BTP directories, subaccounts, entitlements and administrators as code with SAP's Terraform provider, and gate every plan before it can delete anything.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/btp-automation-with-terraform/
- Updated: 2026-11-27
- Reading time: Foundational 8 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

Today an administrator builds a BTP landscape by clicking through the cockpit: a directory here, a subaccount there, a quota, an administrator. A month later nobody can say exactly what was set, or why.

**Infrastructure as code** writes the landscape down instead. Text files say which directories and subaccounts exist, in which region, with which entitlements and which administrators. A tool called **Terraform** reads the files, compares them with what is really there, shows a **plan** of the differences, and makes the changes only when someone approves.

SAP publishes a Terraform provider for BTP, the plug-in that lets Terraform talk to BTP. It is open source and free. It has no official SAP support: questions and bugs go through its public GitHub repository.

The decision for a leader is not "should we use Terraform". It is: which parts of BTP become code, who may approve a plan, and which kinds of plan are refused before a person even sees them.

### Why it matters to the business

**Repeatability.** Calder Pumpworks, the course's fictional pump maker, now has twelve subaccounts in four directories. Adding Augsburg's two subaccounts by hand is a string of cockpit steps that leaves no record of who decided what. As code, it is one reviewed change that anyone can read later, and the same pattern serves the next location.

**A record that auditors accept.** Every change is a pull request: who asked, who approved, what changed. That is the evidence an audit of administrator access asks for.

**Drift shows up.** When someone changes a subaccount in the cockpit, the next plan shows the difference. Without code there is nothing to compare against.

**The risk moves, it doesn't vanish.** A wrong line can do more damage than a wrong click. Change one field and Terraform may delete a subaccount, with every app and service in it, and create an empty one. The plan says so, but only if someone reads it. This is why the review gate matters more than the code.

**Cost.** The provider, Terraform's command-line tool and SAP's exporter cost nothing to download. The cost is people: someone who knows Terraform, a pipeline to run it, and secure storage for its records. SAP's administrator guide is candid that the tool has a real learning curve.

### How SAP does it

As of November 2026, SAP offers these pieces, all open source on GitHub:

- **Terraform Provider for SAP BTP** (`SAP/btp` on the Terraform registry; release 1.28.1, tagged 17 November 2026). It manages directories, subaccounts, entitlements, environment instances, subscriptions, service instances and bindings, role collections and their assignments, and trust to an identity provider ([SAP's infrastructure-as-code page](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/account-administration-using-infrastructure-as-code-8d201e4.md)). SAP states there is no official support; feedback goes through the repository.
- **Terraform exporter for SAP BTP** (`btptf`, release 2.0.1, tagged 23 November 2026). It turns existing directories, subaccounts and Cloud Foundry orgs into Terraform code, so a landscape built by hand can be taken over ([exporter documentation](https://sap.github.io/terraform-exporter-btp/)).
- A **Scripting and Automation Preview** panel in the cockpit that shows the Terraform equivalent of the page you are on ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/scripting-and-automation-preview-7cf9f14.md)).
- For apps inside Cloud Foundry, the Cloud Foundry community's own provider (`cloudfoundry/cloudfoundry`), which SAP's panel uses beside the BTP provider.

SAP's administrator guide recommends Terraform for scalable, repeatable subaccount setup, and says to align with it if the company already uses Terraform or OpenTofu (an open-source fork of Terraform) for AWS, Azure or Google Cloud ([Tools for Account Administration](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/tools-for-account-administration-6bdb3a7.md)).

### What goes in code, and what doesn't

| Layer | Example at Calder | As code? | Tool and owner |
| --- | --- | --- | --- |
| Account structure | Directories, subaccounts, regions, labels | Yes | Terraform, BTP platform team |
| Entitlements and quotas | SAP AI Core plans for the AI directory | Yes | Terraform, BTP platform team |
| Administrators | Global account, directory and subaccount administrators | Yes | Terraform, approved by the second platform administrator |
| Business users' roles | Who may use the order-exceptions agent | No: groups in the identity provider | Security topic's groups |
| Applications | The distributor order-status app | No: a release pipeline | [CI/CD and transport management](https://erpfde.com/topics/btp-cicd-and-transport/) |
| Emergency access | The sealed break-glass administrator | No, on purpose | Security team |

The last row is deliberate. If the pipeline breaks, or a bad change removes administrators, someone must still be able to get in.

### Questions to ask

1. Which BTP objects will be managed as code, and which stay manual, with a reason for each?
2. Who approves a plan for production, and is that a different person from the one who wrote the change?
3. What does the pipeline refuse automatically, before a person sees it (deleting a production subaccount, beta features in production)?
4. Where is Terraform's state file stored, who can read it, and is it encrypted? It can hold secrets.
5. How do we take over the subaccounts that already exist without recreating them?
6. Who supports this when it breaks, given that SAP's provider has no official support?
7. How often do we check for drift, and who acts on it?

### Common misconceptions

- **"Terraform makes BTP safer by itself."** It makes changes repeatable. Without a review gate it repeats mistakes faster, including deletions.
- **"Moving a subaccount to another directory is a small edit."** In the provider it deletes the subaccount and creates a new, empty one. The safe move is done in the cockpit, then recorded in code.
- **"If it's in Git, it's documented."** Only what Terraform manages shows drift. Things clicked in the cockpit and never imported stay invisible.
- **"The protection setting stops all deletions."** Terraform's `prevent_destroy` blocks a plan that would destroy a protected subaccount, but not when someone deletes the subaccount's block from the code.
- **"SAP supports it like any other product."** SAP built it and maintains it in the open, and states there is no official support.

### Key terms

- **Infrastructure as code:** describing platform resources in files that a tool applies, instead of configuring them by hand.
- **Terraform:** HashiCorp's tool that compares configuration files with real resources and plans and applies the differences.
- **Provider:** the plug-in that lets Terraform manage one platform; for BTP, `SAP/btp`.
- **Plan:** the list of creates, updates, replacements and deletions Terraform would make.
- **State:** Terraform's record of the resources it manages, used to compute the next plan.
- **Drift:** a difference between the code and what is really configured, usually from a change made by hand.
- **Import:** taking an existing resource under Terraform's management without recreating it.
- **Terraform exporter for SAP BTP (btptf):** SAP's tool that writes code and import blocks for existing BTP resources.

### Check yourself

1. What is the main business case for managing Calder's BTP account model as code?
   - A. It removes the need for BTP administrators in each team
   - B. Every change becomes repeatable, reviewed and recorded
   - C. It lowers the subscription price of the global account
   - D. It lets SAP support take over the landscape directly

   Answer: B. Code turns each change into a pull request that is reviewed and kept, and the same change can be repeated for Augsburg. Administrators are still needed, and nothing about pricing or SAP support changes.

2. A colleague's change moves the Ext Test subaccount into another directory in the code. What happens if the plan is applied as is?
   - A. The subaccount is moved and keeps everything inside it
   - B. Terraform refuses, because moves are not allowed in BTP
   - C. The subaccount is deleted and an empty one is created
   - D. Only the labels change; the directory stays the same

   Answer: C. The provider doesn't support moves; changing the parent deletes the subaccount and recreates it under the new directory. The safe route is to move it in the cockpit and then update the code and Terraform's records.

3. What does SAP say about support for its Terraform provider for BTP?
   - A. It is covered by the BTP support contract like the cockpit
   - B. It is supported only for Enterprise Edition global accounts
   - C. It is supported once a partner certifies the pipeline
   - D. It is open source with no official SAP support

   Answer: D. SAP's documentation states that the provider is open source under the Apache 2.0 license and has no official SAP support. Issues and requests go through the public GitHub repository, which affects who you plan to call when it breaks.

4. Which item should Calder deliberately keep out of the Terraform code?
   - A. The production subaccounts' administrators
   - B. The sealed break-glass administrator account
   - C. The SAP AI Core entitlement of the AI directory
   - D. The labels that carry cost objects for finance

   Answer: B. Emergency access must work when the pipeline is broken or a bad change has removed administrators. Administrators, entitlements and labels belong in code so they are reviewed and drift is visible.

5. Why does Terraform's state file need the same protection as a password store?
   - A. It holds the BTP contract and its prices
   - B. It is the only backup of the subaccounts' data
   - C. It can hold sensitive values in plain text
   - D. SAP reads it to bill the global account

   Answer: C. The provider hides sensitive fields in command output, but the state file stores them in plain text, so it belongs in encrypted storage with limited access. It is not a data backup and SAP doesn't read it.

6. Calder already created four subaccounts by hand. What is the right way to bring them under Terraform?
   - A. Delete them and let Terraform create them again
   - B. Import them, for example with SAP's exporter
   - C. Leave them out; Terraform will find them anyway
   - D. Rename them so Terraform treats them as new

   Answer: B. Import takes existing resources under management without recreating them, and SAP's exporter writes the code and import blocks. Terraform never sees resources it neither created nor imported, so leaving them out hides their drift.

## Deep layer

### Mental model

Terraform keeps three things apart and compares them:

1. **Configuration**: the `.tf` files. What you want.
2. **State**: Terraform's record of the objects it manages and their last known values. What it thinks exists.
3. **Reality**: what BTP really holds, read through the provider.

`terraform plan` refreshes state from reality, compares it with the configuration and lists actions. `terraform apply` carries them out. Everything else follows from this: an object that is neither created by Terraform nor imported is not in state, so Terraform can't see its drift; an attribute the provider can't change in place turns into "delete, then create"; and a plan is the one artifact a reviewer must read.

For an architect, the useful framing is that **the account model is data and Terraform is the delivery mechanism**. Calder's model from [the account model topic](https://erpfde.com/topics/btp-account-model/) already says what should exist. This topic turns that model into code, then puts a gate in front of every plan.

### How it works

```mermaid
flowchart LR
  M[Account model<br/>JSON] --> G[Generator]
  G --> C[.tf files<br/>in Git]
  C --> P[terraform plan]
  S[(State<br/>encrypted)] --> P
  B[BTP via<br/>provider] --> P
  P --> J[Plan JSON]
  J --> R{Review gate<br/>P01-P05}
  R -- FAIL --> X[Stop]
  R -- pass --> A[Approval]
  A --> AP[terraform apply]
  AP --> B
  AP --> S
```

#### The provider and how it signs in

The provider is declared as `SAP/btp` with a pinned version, and configured with the **subdomain of the global account**. It reaches BTP through the btp CLI server (`https://cli.btp.cloud.sap` by default). The repository's documentation describes four ways to authenticate ([provider documentation](https://github.com/SAP/terraform-provider-btp/blob/main/docs/index.md)):

| Method | How | Fit |
| --- | --- | --- |
| User and password | `BTP_USERNAME` and `BTP_PASSWORD` environment variables | Local trials. Not compatible with SAP Universal ID; no two-factor authentication |
| X.509 certificate | A technical user in a custom identity provider (SAP Cloud Identity Services) with a client certificate | Pipelines |
| JWT bearer assertion | A token from a custom identity provider in `BTP_ASSERTION` | Pipelines that use federated identity, such as a CI system's OIDC token |
| btp CLI session | `USE_BTPCLI_SESSION=true` after `btp login --sso` | A person at a desk; not supported in CI/CD |

Explicit provider settings win over environment variables, and setting one method's attribute makes the provider ignore environment variables of another.

#### What the provider manages

The resource list in release 1.28.1 has three levels, matching the account model:

| Level | Resources (prefix `btp_`) |
| --- | --- |
| Global account | `globalaccount_role_collection_assignment`, `globalaccount_role_collection`, `globalaccount_security_settings`, `globalaccount_trust_configuration`, `globalaccount_resource_provider` |
| Directory | `directory`, `directory_entitlement`, `directory_role_collection`, `directory_role_collection_assignment` |
| Subaccount | `subaccount`, `subaccount_entitlement`, `subaccount_environment_instance`, `subaccount_service_instance`, `subaccount_service_binding`, `subaccount_subscription`, `subaccount_role_collection`, `subaccount_role_collection_assignment`, `subaccount_security_settings`, `subaccount_trust_configuration`, destinations |

Inside a Cloud Foundry org, spaces, apps and space roles belong to the separate `cloudfoundry/cloudfoundry` provider (release 1.19.0). The provider also offers **actions**, such as `btp_add_me_as_subaccount_admin` and `btp_restore_subaccount`, which do something once and change nothing in state. SAP's documentation recommends the role collection assignment resource instead of the add-me action for a consistent setup.

A few attributes carry most of the design:

- `btp_subaccount`: `name`, `region` and `subdomain` are required. The subdomain can't change after creation. `usage` takes `USED_FOR_PRODUCTION` or `NOT_USED_FOR_PRODUCTION`. `labels` is a map of label names to sets of values. `parent_id` points at a directory, or is left out for the global account.
- `btp_directory`: `features` takes `DEFAULT`, `ENTITLEMENTS` and `AUTHORIZATIONS` (the last only with entitlements), matching the directory features of the account model.
- `btp_directory_entitlement` and `btp_subaccount_entitlement`: `service_name` and `plan_name` use technical names (`aicore`, not "SAP AI Core"). `amount` is only allowed for plans with a numeric quota; setting it on another plan category fails.

#### What turns into "delete, then create"

The provider documents which changes it can't make in place ([btp_subaccount](https://github.com/SAP/terraform-provider-btp/blob/main/docs/resources/subaccount.md)):

| Change | What the plan does |
| --- | --- |
| `parent_id` (move to another directory) | Deletes the subaccount and everything that depends on it, creates a new one |
| `subdomain` | Can't be changed after creation; the plan replaces the subaccount |
| `skip_auto_entitlement` switched to or from `true` | Replaces the subaccount |
| Labels, description, `beta_enabled`, `usage` | Updated in place |

Terraform's JSON plan shows a replacement as the actions `["delete", "create"]`, usually with an `action_reason` such as `replace_because_cannot_update` ([JSON output format](https://developer.hashicorp.com/terraform/internals/json-format)). That pair is what the review gate looks for.

To move a subaccount safely, the provider's guide gives a workaround: move it in the cockpit or btp CLI, back up state and code, remove the subaccount from state, change `parent_id`, and import it again ([Move of Subaccounts](https://github.com/SAP/terraform-provider-btp/blob/main/guides/MOVESUBACCOUNT.md)).

#### Deleting, and what protects you

When Terraform deletes a subaccount and the delete fails because resources are still active, the provider retries with **force delete**. That starts a pending-deletion period of several days, after which the subaccount is gone for good. Costs can still accrue during the period, and the subaccount drops out of state. Force deletion works only if it is enabled in the global account's settings and the subaccount isn't marked as used for production. The `usage` flag is therefore more than a label.

Terraform's own `prevent_destroy` lifecycle setting rejects any plan that would destroy the protected object. Its documentation is precise about the gap: it doesn't stop a destroy when the resource's configuration is removed ([lifecycle](https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle)). A reviewer, or a gate, still has to catch a deleted block.

#### Who becomes administrator

SAP's documentation says whoever creates a subaccount is automatically assigned to it as an administrator ([Create a Subaccount](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/create-a-subaccount-05280a1.md)). When a pipeline creates subaccounts, its technical user becomes administrator of every one. Treat that user as a highly privileged account: certificate in a secret store, used only by the pipeline, its sign-ins reviewed.

#### Taking over what already exists

Terraform's `import` block takes an existing object under management: `to` names the resource address, `id` the BTP ID (for a subaccount, its GUID). Newer provider releases also accept identity-based imports. Writing import blocks and matching configuration by hand for dozens of objects is slow, which is what SAP's exporter is for: `btptf create-json` lists what a subaccount, directory or Cloud Foundry org holds, you edit that list, and `btptf export-by-json` writes refined code plus import blocks. Version 2 needs Terraform CLI 1.14 or newer and doesn't support OpenTofu. It writes no state file, so you can add a remote backend before the first import ([exporter concepts](https://sap.github.io/terraform-exporter-btp/concepts/)).

#### Drift

The provider's guide recommends `terraform plan -refresh-only -detailed-exitcode`: exit code 0 means no drift, 2 means differences, 1 an error ([Drift Detection](https://github.com/SAP/terraform-provider-btp/blob/main/guides/DRIFTDETECTION.md)). Two limits matter. Since provider 1.26.0, role collection assignments are read back, so the user running Terraform needs a read role in each scope, such as *Subaccount Viewer*; a global account role doesn't grant read access inside subaccounts. And the `parameters` of service instances aren't tracked.

#### Sensitive values

Fields such as service instance `parameters` are marked sensitive, so the command line hides them. The state file still stores them in plain text, and so does the JSON form of a saved plan ([Sensitive data](https://github.com/SAP/terraform-provider-btp/blob/main/guides/SENSITIVEDATA.md)). Both belong in encrypted storage, never in Git.

### Build it yourself

**Before you start:** finish [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/). This topic builds on the account model from [The BTP account model](https://erpfde.com/topics/btp-account-model/); if you did its exercise, the script reads your `unit21/calder_account_model.json`. If you didn't, add `--sample` to every command in Steps 3 to 6 and the script uses its own copy of the reviewed model. The output is the same.

You will turn Calder's account model into Terraform files, simulate the first plan, review a colleague's change request that would delete two subaccounts, and write the design document `unit21/btp_terraform_design.md`. An optional last step runs real Terraform against your free trial.

```mermaid
flowchart LR
  J[calder_account_model.json] --> G[--generate]
  G --> T[unit21/btp-terraform/*.tf]
  J --> PC[--plan create]
  J --> CH[--plan change<br/>CR-0412]
  PC --> K[--check-plan]
  CH --> K
  K --> W[--write]
  W --> D[btp_terraform_design.md]
```

> **Note** **New words.** A **configuration file** (`.tf`) is a text file in Terraform's language, HCL, that describes resources. A **resource block** describes one object, such as one subaccount. A **plan** is Terraform's list of changes. **JSON** is a text format for structured data; Terraform can write a plan as JSON so other programs can read it. An **exit code** is the number a program returns when it ends: 0 means fine, other numbers mean "look at this".

Steps 1 to 6 talk to no SAP system and don't need Terraform installed. The `--plan` option is a **course stand-in** that compares two versions of the model the way `terraform plan` compares state and configuration, and writes the result in Terraform's JSON plan format. The `--check-plan` gate reads that format, so it also reads a real plan from Step 7.

#### What you need

- The course folder `orchestrate-course` with its `.venv`.
- No account and no key for Steps 1 to 6. The script uses only Python's built-in modules, so `requirements.txt` doesn't change.
- For the optional Step 7: your free BTP trial and Terraform CLI 1.14 or newer, a free download from HashiCorp.
- Time: about 40 minutes, plus 20 for Step 7.

#### Step 1: Open your course folder and turn on the virtual environment

1. Open VS Code, then **File > Open Folder** and choose `orchestrate-course`.
2. Open a terminal with **Terminal > New Terminal**.
3. Turn on the virtual environment:
   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. Make the `unit21` folder if it doesn't exist yet:
   - **Windows (PowerShell):**

     ```powershell
     New-Item -ItemType Directory -Force unit21
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p unit21
     ```

You should see `(.venv)` at the start of the prompt.

#### Step 2: Create the script

1. In VS Code, create the file `unit21/btp_iac.py`.
2. Paste the code below and save.

```python
"""Calder's BTP account model as Terraform code, plus a review gate for Terraform plans.

Usage (run from the orchestrate-course folder):
  python unit21/btp_iac.py --generate            write Terraform files to unit21/btp-terraform/
  python unit21/btp_iac.py --plan create         simulate the first plan: imports and creates
  python unit21/btp_iac.py --plan change         simulate the plan for change request CR-0412
  python unit21/btp_iac.py --check-plan FILE     review a plan in Terraform's JSON plan format
  python unit21/btp_iac.py --write               write unit21/btp_terraform_design.md (the deliverable)

Options:
  --sample      use the built-in reviewed account model instead of unit21/calder_account_model.json
  --force       let --plan change overwrite unit21/calder_account_model_cr0412.json

--check-plan also reads a real plan: terraform plan -out=tfplan, then
terraform show -json tfplan > tfplan.json. Built-in modules only, no account, no network.
--plan is a course stand-in for terraform plan, not Terraform. Calder Pumpworks is fictional;
IDs, e-mail addresses, CR-0412 and rules P01-P05 are course labels, not SAP values.
"""
import argparse
import copy
import json
import re
import sys
from pathlib import Path

MODEL_FILE = Path("unit21/calder_account_model.json")
CR_FILE = Path("unit21/calder_account_model_cr0412.json")
TF_DIR = Path("unit21/btp-terraform")
REPORT_FILE = Path("unit21/btp_terraform_design.md")
FENCE = "`" * 3

PROVIDER_VERSION = "1.28.1"     # SAP/btp on the Terraform registry, tagged 2026-11-17
SERVICE_NAMES = {"SAP AI Core": "aicore"}   # cockpit name -> technical service name
ADMIN_ROLES = {"Global Account Administrator", "Directory Administrator", "Subaccount Administrator"}
# Subaccounts that already exist (created by hand in 2026). Course GUIDs, not real ones.
EXISTING = {
    "AI Test": "3f1a7c20-0b6d-4e55-9c1e-5a0d7e2b1a01",
    "AI Prod": "3f1a7c20-0b6d-4e55-9c1e-5a0d7e2b1a02",
    "Ext Test": "3f1a7c20-0b6d-4e55-9c1e-5a0d7e2b1a03",
    "Ext Prod": "3f1a7c20-0b6d-4e55-9c1e-5a0d7e2b1a04",
}
# Personnel number -> sign-in name (the course's platform users, see the security topic)
USERS = {
    "00100280": "group.controller@calder-pumpworks.example",
    "00100288": "integration.dev@calder-pumpworks.example",
    "00100290": "enterprise.architect@calder-pumpworks.example",
    "00100292": "integration.lead@calder-pumpworks.example",
    "00100316": "btp.admin1@calder-pumpworks.example",
    "00100317": "btp.admin2@calder-pumpworks.example",
}


# ---------------------------------------------------------------- the model

def sample_model():
    """The reviewed account model: the account model topic's draft with its exercise done."""
    def labels(stage, team, cost, mail, **more):
        out = {"Stage": [stage], "Owner team": [team], "Cost object": [cost],
               "Contacts": [f"{mail}@calder-pumpworks.example"]}
        out.update(more)
        return out

    def sub(name, parent, stage, sd, admins, lab, region="us10", ent=None, beta=False):
        return {"type": "subaccount", "name": name, "parent": parent, "stage": stage,
                "region": region, "subdomain": sd, "used_for_production": stage == "prod",
                "beta_enabled": beta, "admins": admins, "labels": lab, "entitlements": ent or {}}

    two = ["00100316", "00100317"]
    ai = {"SAP AI Core/extended": 1}
    proc = {"Process": ["o2c", "p2p"]}
    nodes = [
        {"type": "directory", "name": "Platform", "parent": None, "features": [], "admins": [],
         "labels": {}, "entitlements": {}},
        {"type": "directory", "name": "AI and agents", "parent": None,
         "features": ["entitlements", "users"], "admins": ["00100290", "00100288"],
         "labels": {"Owner team": ["AI platform"], "Cost object": ["CP10-920"],
                    "Contacts": ["ai-platform@calder-pumpworks.example"]},
         "entitlements": {"SAP AI Core/extended": 3}},
        {"type": "directory", "name": "Extensions", "parent": None, "features": [], "admins": [],
         "labels": {}, "entitlements": {}},
        {"type": "directory", "name": "Augsburg", "parent": None, "features": [], "admins": [],
         "labels": {"Residency": ["EU"]}, "entitlements": {}},
        sub("Integration Dev", "Platform", "dev", "calder-int-dev", ["00100288"],
            labels("Dev", "Integration", "CP10-910", "btp-platform")),
        sub("Integration Test", "Platform", "test", "calder-int-test", ["00100288"],
            labels("Test", "Integration", "CP10-910", "btp-platform")),
        sub("Integration Prod", "Platform", "prod", "calder-int-prod", ["00100292", "00100316"],
            labels("Prod", "Integration", "CP10-910", "btp-platform")),
        sub("AI Dev", "AI and agents", "dev", "calder-ai-dev", ["00100288"],
            {"Stage": ["Dev"], **proc}, ent=ai),
        sub("AI Test", "AI and agents", "test", "calder-ai-test", ["00100288"],
            {"Stage": ["Test"], **proc}, ent=ai),
        sub("AI Prod", "AI and agents", "prod", "calder-ai-prod", ["00100290", "00100316"],
            {"Stage": ["Prod"], **proc}, ent=ai),
        sub("Ext Dev", "Extensions", "dev", "calder-ext-dev", ["00100288"],
            labels("Dev", "Apps", "CP10-910", "apps-team")),
        sub("Ext Test", "Extensions", "test", "calder-ext-test", ["00100288"],
            labels("Test", "Apps", "CP10-910", "apps-team")),
        sub("Ext Prod", "Extensions", "prod", "calder-ext-prod", two,
            labels("Prod", "Apps", "CP10-910", "apps-team")),
        sub("Sandbox", None, "sandbox", "calder-sandbox", two,
            {"Expires": ["2027-03-31"], **labels("Sandbox", "BTP platform", "CP10-910", "btp-platform")},
            beta=True),
        sub("Augsburg Dev", "Augsburg", "dev", "calder-aug-dev", ["00100288"],
            labels("Dev", "Apps", "CP20-910", "apps-team"), region="eu10"),
        sub("Augsburg Prod", "Augsburg", "prod", "calder-aug-prod", two,
            labels("Prod", "Apps", "CP20-910", "apps-team"), region="eu10"),
    ]
    return {"as_of": "2026-11-26",
            "global_account": {"name": "Calder Pumpworks", "admins": two, "viewers": ["00100280"]},
            "nodes": nodes}


def change_request(model):
    """CR-0412 as a colleague proposed it on Friday 2026-11-27: six edits to the model."""
    cr = copy.deepcopy(model)
    by = {n["name"]: n for n in cr["nodes"]}
    by["Ext Test"]["parent"] = "Platform"                          # "tidy up": move Ext Test
    by["Integration Prod"]["subdomain"] = "calder-integration-prod"  # "match the new naming"
    by["Augsburg Prod"]["beta_enabled"] = True                    # "try a beta service"
    by["AI Dev"]["labels"]["Process"] = ["o2c", "p2p", "r2r"]      # the close cockpit work
    by["AI Prod"]["admins"] = by["AI Prod"]["admins"] + ["00100288"]  # "so I can debug"
    cr["nodes"] = [n for n in cr["nodes"] if n["name"] != "Sandbox"]  # "nobody uses it"
    cr["as_of"] = "2026-11-27 (CR-0412 proposed)"
    return cr


def load(path, strict=True):
    if not path.exists():
        sys.exit(f"No model file {path}. Finish the account model topic's exercise, "
                 "or add --sample to use the built-in reviewed model.")
    try:
        model = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        sys.exit(f"{path} is not valid JSON (line {e.lineno}, column {e.colno}): {e.msg}")
    names = {n["name"] for n in model["nodes"]}
    for n in model["nodes"]:
        if n["parent"] is not None and n["parent"] not in names:
            sys.exit(f"{path}: {n['name']} names parent '{n['parent']}', which is not in the model")
        if strict and n["type"] == "subaccount" and n["beta_enabled"] and n["used_for_production"]:
            sys.exit(f"{path}: {n['name']} is production with beta features on. Run "
                     "python unit21/account_model.py --check and fix the model first.")
    return model


# ---------------------------------------------------------------- model -> resources

def slug(name):
    return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")


def plan_name(key):
    service, _, plan = key.partition("/")
    return SERVICE_NAMES.get(service, service), plan


def resources(model):
    """Every Terraform resource the model needs, as (address, type, attributes, refs, protect)."""
    out = []
    by = {n["name"]: n for n in model["nodes"]}
    ga = model["global_account"]
    for role, people in (("Global Account Administrator", ga["admins"]),
                         ("Global Account Viewer", ga.get("viewers", []))):
        for p in people:
            short = "ga_admin" if "Administrator" in role else "ga_viewer"
            out.append((f"btp_globalaccount_role_collection_assignment.{short}_{p}",
                        "btp_globalaccount_role_collection_assignment",
                        {"role_collection_name": role, "user_name": f"var.users[{p}]",
                         "origin": "var.platform_origin"}, {}, False))
    for d in [n for n in model["nodes"] if n["type"] == "directory"]:
        s = slug(d["name"])
        attrs = {"name": d["name"]}
        feats = d.get("features", [])
        if feats:
            attrs["features"] = ["DEFAULT"] + (["ENTITLEMENTS"] if "entitlements" in feats else []) \
                + (["AUTHORIZATIONS"] if "users" in feats else [])
        if "users" in feats:
            attrs["subdomain"] = f"calder-{s.replace('_', '-')}"
        if d.get("labels"):
            attrs["labels"] = d["labels"]
        refs = {"parent_id": f"btp_directory.{slug(d['parent'])}.id"} if d["parent"] else {}
        out.append((f"btp_directory.{s}", "btp_directory", attrs, refs, False))
        for key, amount in d.get("entitlements", {}).items():
            svc, plan = plan_name(key)
            out.append((f"btp_directory_entitlement.{s}_{svc}_{plan}", "btp_directory_entitlement",
                        {"service_name": svc, "plan_name": plan, "amount": amount},
                        {"directory_id": f"btp_directory.{s}.id"}, False))
        for p in d.get("admins", []):
            out.append((f"btp_directory_role_collection_assignment.{s}_admin_{p}",
                        "btp_directory_role_collection_assignment",
                        {"role_collection_name": "Directory Administrator",
                         "user_name": f"var.users[{p}]", "origin": "var.platform_origin"},
                        {"directory_id": f"btp_directory.{s}.id"}, False))
    for sa in [n for n in model["nodes"] if n["type"] == "subaccount"]:
        s = slug(sa["name"])
        attrs = {"name": sa["name"], "subdomain": sa["subdomain"], "region": sa["region"],
                 "usage": "USED_FOR_PRODUCTION" if sa["used_for_production"] else "NOT_USED_FOR_PRODUCTION",
                 "beta_enabled": sa["beta_enabled"], "labels": sa.get("labels", {})}
        refs = {"parent_id": f"btp_directory.{slug(sa['parent'])}.id"} if sa["parent"] else {}
        out.append((f"btp_subaccount.{s}", "btp_subaccount", attrs, refs, sa["used_for_production"]))
        for key, amount in sa.get("entitlements", {}).items():
            svc, plan = plan_name(key)
            dep = [r[0] for r in out if r[1] == "btp_directory_entitlement"
                   and sa["parent"] and r[0].startswith(f"btp_directory_entitlement.{slug(sa['parent'])}_{svc}_{plan}")]
            out.append((f"btp_subaccount_entitlement.{s}_{svc}_{plan}", "btp_subaccount_entitlement",
                        {"service_name": svc, "plan_name": plan, "amount": amount},
                        {"subaccount_id": f"btp_subaccount.{s}.id", "depends_on": dep}, False))
        for p in sa["admins"]:
            out.append((f"btp_subaccount_role_collection_assignment.{s}_admin_{p}",
                        "btp_subaccount_role_collection_assignment",
                        {"role_collection_name": "Subaccount Administrator",
                         "user_name": f"var.users[{p}]", "origin": "var.platform_origin"},
                        {"subaccount_id": f"btp_subaccount.{s}.id"}, False))
    return out


# ---------------------------------------------------------------- HCL output

def hcl_value(v, indent):
    pad = "  " * indent
    if isinstance(v, bool):
        return "true" if v else "false"
    if isinstance(v, (int, float)):
        return str(v)
    if isinstance(v, str):
        m = re.fullmatch(r"var\.users\[(\d+)\]", v)
        if m:
            return f'var.users["{m.group(1)}"]'
        if v.startswith("var."):
            return v
        return json.dumps(v)
    if isinstance(v, list):
        return "[" + ", ".join(hcl_value(x, indent) for x in v) + "]"
    if isinstance(v, dict):
        width = max(len(json.dumps(k)) for k in v)
        rows = [f"{pad}  {json.dumps(k):<{width}} = {hcl_value(x, indent + 1)}" for k, x in v.items()]
        return "{\n" + "\n".join(rows) + f"\n{pad}}}"
    raise ValueError(v)


def hcl_resource(address, attrs, refs, protect):
    rtype, name = address.split(".", 1)
    body = {k: v for k, v in refs.items() if k != "depends_on"}
    body.update(attrs)
    width = max(len(k) for k in body)
    lines = [f'resource "{rtype}" "{name}" {{']
    for k, v in body.items():
        val = v if (k in refs and k != "depends_on") else hcl_value(v, 1)
        lines.append(f"  {k:<{width}} = {val}")
    if refs.get("depends_on"):
        lines.append(f"  depends_on = [{', '.join(refs['depends_on'])}]")
    if protect:
        lines += ["", "  lifecycle {", "    prevent_destroy = true", "  }"]
    lines.append("}")
    return "\n".join(lines)


def generate(model):
    TF_DIR.mkdir(parents=True, exist_ok=True)
    res = resources(model)
    files = {}
    files["versions.tf"] = f"""terraform {{
  required_version = ">= 1.14.0"
  required_providers {{
    btp = {{
      source  = "SAP/btp"
      version = "{PROVIDER_VERSION}"
    }}
  }}
}}
"""
    files["provider.tf"] = """# Credentials never go in this file. Locally: BTP_USERNAME and BTP_PASSWORD
# (or the btp CLI session). In a pipeline: a technical user with an X.509 certificate.
provider "btp" {
  globalaccount = var.globalaccount
}
"""
    files["variables.tf"] = """variable "globalaccount" {
  description = "Subdomain of the global account (cockpit: global account overview)"
  type        = string
}

variable "platform_origin" {
  description = "Origin key of the identity provider that holds platform users"
  type        = string
  default     = "calder-platform"
}

variable "users" {
  description = "Personnel number -> sign-in name of each platform user"
  type        = map(string)
}
"""
    users = {p: USERS[p] for p in sorted({r[2]["user_name"][10:-1] for r in res if "user_name" in r[2]})}
    files["terraform.tfvars.example"] = (
        '# Copy to terraform.tfvars and fill in. terraform.tfvars stays out of Git.\n'
        'globalaccount   = "<your global account subdomain>"\n'
        'platform_origin = "calder-platform"\n'
        "users = " + hcl_value(users, 0) + "\n")
    groups = {"global_account.tf": [], "directories.tf": [], "subaccounts.tf": [], "access.tf": []}
    for address, rtype, attrs, refs, protect in res:
        if rtype.startswith("btp_globalaccount"):
            f = "global_account.tf"
        elif rtype.endswith("role_collection_assignment"):
            f = "access.tf"
        elif rtype.startswith("btp_directory"):
            f = "directories.tf"
        else:
            f = "subaccounts.tf"
        groups[f].append(hcl_resource(address, attrs, refs, protect))
    for f, blocks in groups.items():
        files[f] = f"# Generated from the account model on {model['as_of']}. Edit the model, not this file.\n\n" \
            + "\n\n".join(blocks) + "\n"
    imports = []
    for name, guid in EXISTING.items():
        if any(r[0] == f"btp_subaccount.{slug(name)}" for r in res):
            imports.append(f'import {{\n  to = btp_subaccount.{slug(name)}\n  id = "{guid}"\n}}')
    files["imports.tf"] = ("# Subaccounts created by hand before Terraform. Remove this file after the first apply.\n\n"
                           + "\n\n".join(imports) + "\n")
    files[".gitignore"] = ".terraform/\n*.tfstate\n*.tfstate.*\ntfplan\ntfplan.json\nterraform.tfvars\n"
    for f, text in files.items():
        (TF_DIR / f).write_text(text, encoding="utf-8")
    counts = {}
    for r in res:
        counts[r[1]] = counts.get(r[1], 0) + 1
    print(f"Wrote {len(files)} files to {TF_DIR}/ for {len(res)} resources:")
    for t, c in counts.items():
        print(f"  {c:>3}  {t}")
    print(f"  {len(imports):>3}  import blocks for subaccounts that already exist")
    print(f"  {sum(1 for r in res if r[4]):>3}  production subaccounts with prevent_destroy")


# ---------------------------------------------------------------- the plan stand-in

REPLACE_ON = {"btp_subaccount": {"subdomain", "region", "parent_id"}}


def state_of(model):
    """Resources keyed by address, with references written as the address they point to."""
    out = {}
    for address, rtype, attrs, refs, protect in resources(model):
        values = dict(attrs)
        for k, v in refs.items():
            if k != "depends_on":
                values[k] = v
        if "user_name" in values:          # what the plan shows: the sign-in name and origin
            values["user_name"] = USERS[values["user_name"][10:-1]]
            values["origin"] = "calder-platform"
        out[address] = (rtype, values, protect)
    return out


def change_entry(address, rtype, actions, before, after, reason=None, importing=None):
    entry = {"address": address, "type": rtype, "name": address.split(".", 1)[1],
             "provider_name": "registry.terraform.io/sap/btp",
             "change": {"actions": actions, "before": before, "after": after}}
    if reason:
        entry["action_reason"] = reason
    if importing:
        entry["change"]["importing"] = {"id": importing}
    return entry


def simulate(old, new, notes):
    """Compare two models the way terraform plan compares state and configuration."""
    before = state_of(old) if old else {}
    after = state_of(new)
    changes = []
    for address, (rtype, values, protect) in after.items():
        if address not in before:
            guid = None
            if old is None and rtype == "btp_subaccount":
                guid = next((g for n, g in EXISTING.items() if f"btp_subaccount.{slug(n)}" == address), None)
            if guid:
                changes.append(change_entry(address, rtype, ["no-op"], values, values, importing=guid))
            else:
                changes.append(change_entry(address, rtype, ["create"], None, values))
            continue
        _, old_values, _ = before[address]
        diff = {k for k in set(values) | set(old_values) if values.get(k) != old_values.get(k)}
        if not diff:
            changes.append(change_entry(address, rtype, ["no-op"], values, values))
            continue
        if diff & REPLACE_ON.get(rtype, set()) or rtype.endswith("role_collection_assignment"):
            changes.append(change_entry(address, rtype, ["delete", "create"], old_values, values,
                                        reason="replace_because_cannot_update"))
            if protect:
                notes.append(f"{address} has prevent_destroy: real Terraform stops the plan with an error here")
        else:
            changes.append(change_entry(address, rtype, ["update"], old_values, values))
    for address, (rtype, old_values, protect) in before.items():
        if address not in after:
            changes.append(change_entry(address, rtype, ["delete"], old_values, None))
            if protect:
                notes.append(f"{address} is gone from the configuration, so prevent_destroy can't protect it")
    return {"format_version": "1.2", "terraform_version": "course stand-in",
            "resource_changes": changes}


def summary(plan):
    counts = {"import": 0, "create": 0, "update": 0, "replace": 0, "delete": 0}
    for rc in plan.get("resource_changes", []):
        a = rc["change"]["actions"]
        if rc["change"].get("importing"):
            counts["import"] += 1
        if a == ["create"]:
            counts["create"] += 1
        elif a == ["update"]:
            counts["update"] += 1
        elif a == ["delete"]:
            counts["delete"] += 1
        elif sorted(a) == ["create", "delete"]:
            counts["replace"] += 1
    return ", ".join(f"{v} to {k}" for k, v in counts.items())


# ---------------------------------------------------------------- the review gate

def check_plan(plan):
    """Course rules P01-P05 on a plan in Terraform's JSON plan format."""
    findings = []
    changes = plan.get("resource_changes", [])
    new_subaccounts = {rc["address"] for rc in changes
                       if rc["type"] == "btp_subaccount" and rc["change"]["actions"] == ["create"]}
    prod, ids = set(), {}
    for rc in changes:
        if rc["type"] == "btp_subaccount":
            for side in ("before", "after"):
                v = rc["change"].get(side) or {}
                if v.get("usage") == "USED_FOR_PRODUCTION":
                    prod.add(rc["address"])
                if v.get("id"):                   # a real plan names the parent by its ID
                    ids[v["id"]] = rc["address"]

    def add(level, rule, address, text):
        findings.append((level, rule, address, text))

    for rc in changes:
        addr, rtype = rc["address"], rc["type"]
        actions = rc["change"]["actions"]
        before = rc["change"].get("before") or {}
        after = rc["change"].get("after") or {}
        replace = sorted(actions) == ["create", "delete"]
        if rtype in ("btp_subaccount", "btp_directory") and replace:
            changed = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k))
            add("FAIL", "P01", addr, "replace: deletes it with everything inside, then creates an empty one "
                f"(changed: {', '.join(changed)})")
        if rtype == "btp_subaccount" and actions == ["delete"]:
            if before.get("usage") == "USED_FOR_PRODUCTION":
                add("FAIL", "P02", addr, "deletes a production subaccount")
            else:
                add("WARN", "P02", addr, "deletes a subaccount; confirm with its owner team that it is empty")
        if rtype == "btp_subaccount" and after.get("beta_enabled") is True and not before.get("beta_enabled") \
                and after.get("usage") == "USED_FOR_PRODUCTION":
            add("FAIL", "P03", addr, "switches on beta features in production; this can't be switched off again")
        if rtype == "btp_subaccount" and before.get("usage") == "USED_FOR_PRODUCTION" \
                and after and after.get("usage") != "USED_FOR_PRODUCTION":
            add("FAIL", "P05", addr, "removes the 'Used for production' flag")
        if rtype.endswith("role_collection_assignment") and actions != ["no-op"]:
            role = (after or before).get("role_collection_name", "")
            sid = (after or before).get("subaccount_id", "")
            parent = ids.get(sid, sid.removesuffix(".id"))
            scope_is_prod = rtype.startswith("btp_globalaccount") or parent in prod
            if role in ADMIN_ROLES and scope_is_prod and parent not in new_subaccounts:
                who = (after or before).get("user_name", "?")
                add("WARN", "P04", addr, f"{'/'.join(actions)} {role} for {who}: "
                    "needs the second platform administrator's approval")
    order = {"FAIL": 0, "WARN": 1}
    findings.sort(key=lambda f: (order[f[0]], f[1], f[2]))
    return findings


def print_findings(findings, plan):
    print(f"Plan: {summary(plan)}.")
    for level, rule, addr, text in findings:
        print(f"{level:<4} {rule} {addr}: {text}")
    fails = sum(1 for f in findings if f[0] == "FAIL")
    warns = sum(1 for f in findings if f[0] == "WARN")
    print(f"{fails} FAIL, {warns} WARN" + (": do not apply" if fails else ": may be applied after review"))
    return fails


# ---------------------------------------------------------------- the deliverable

def write_report(model, cr_findings, cr_plan):
    res = resources(model)
    rows = "\n".join(f"| `{f[2]}` | {f[0]} {f[1]} | {f[3]} |" for f in cr_findings) or "| (none) | | |"
    text = f"""# Calder Pumpworks: SAP BTP as code

As of {model['as_of']}. Calder Pumpworks is fictional; every value here is a course value.

### What Terraform owns

- The global account's administrator and viewer assignments, {sum(1 for n in model['nodes'] if n['type'] == 'directory')} directories, {sum(1 for n in model['nodes'] if n['type'] == 'subaccount')} subaccounts, entitlements and the administrator role collection assignments: {len(res)} resources.
- Generated from `unit21/calder_account_model.json` into `unit21/btp-terraform/`. People change the model; the generator writes the code.
- Not owned here: applications (MTA and the transport service), destinations, business users' roles (groups from the identity provider), the break-glass user.

### Provider and tools

- Terraform Provider for SAP BTP `SAP/btp` {PROVIDER_VERSION}, pinned in `versions.tf`. Open source, no official SAP support.
- Terraform CLI 1.14 or newer (the exporter's minimum).
- Terraform exporter for SAP BTP (`btptf`) for subaccounts created by hand.

### Change request CR-0412 (proposed 2026-11-27)

Plan: {summary(cr_plan)}.

| Resource | Result | Finding |
| --- | --- | --- |
{rows}

### Pipeline gates

1. Pull request changes the model; the generator runs; reviewers read the diff of the `.tf` files.
2. `terraform plan -out=tfplan`, then `terraform show -json tfplan > tfplan.json`.
3. `python unit21/btp_iac.py --check-plan tfplan.json`; any FAIL stops the pipeline.
4. A platform administrator approves; `terraform apply tfplan` runs as the pipeline's technical user.
5. Weekly: `terraform plan -refresh-only -detailed-exitcode`; exit code 2 opens a drift ticket.

### Decision record

- **Context:**
- **Options:**
- **Decision:**
- **Consequences:**

### Open questions

1. Where is the state stored, who can read it, and how is it locked?
2. When does the AI platform team get its own state and pipeline?
"""
    REPORT_FILE.write_text(text, encoding="utf-8")
    print(f"Wrote {REPORT_FILE}")


# ---------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description="Calder's BTP account model as Terraform code")
    g = ap.add_mutually_exclusive_group(required=True)
    g.add_argument("--generate", action="store_true")
    g.add_argument("--plan", choices=["create", "change"])
    g.add_argument("--check-plan", metavar="FILE")
    g.add_argument("--write", action="store_true")
    ap.add_argument("--sample", action="store_true")
    ap.add_argument("--force", action="store_true")
    a = ap.parse_args()

    if a.check_plan:
        path = Path(a.check_plan)
        if not path.exists():
            sys.exit(f"No plan file {path}. Run --plan create or --plan change first.")
        try:
            raw = path.read_bytes()      # Windows PowerShell 5.1 writes > redirects as UTF-16
            enc = "utf-16" if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig"
            plan = json.loads(raw.decode(enc))
        except json.JSONDecodeError as e:
            sys.exit(f"{path} is not JSON ({e.msg}). Use terraform show -json, not the plan file itself.")
        sys.exit(2 if print_findings(check_plan(plan), plan) else 0)

    model = sample_model() if a.sample else load(MODEL_FILE)
    if a.generate:
        generate(model)
    elif a.plan == "create":
        notes = []
        plan = simulate(None, model, notes)
        out = Path("unit21/tfplan_create.json")
        out.write_text(json.dumps(plan, indent=2), encoding="utf-8")
        print(f"Wrote {out}. Plan: {summary(plan)}.")
    elif a.plan == "change":
        if not CR_FILE.exists() or a.force:
            CR_FILE.write_text(json.dumps(change_request(model), indent=2), encoding="utf-8")
            print(f"Wrote {CR_FILE}: the model as CR-0412 proposes it.")
        notes = []
        plan = simulate(model, load(CR_FILE, strict=False), notes)
        out = Path("unit21/tfplan_cr0412.json")
        out.write_text(json.dumps(plan, indent=2), encoding="utf-8")
        print(f"Wrote {out}. Plan: {summary(plan)}.")
        for n in notes:
            print(f"note: {n}")
    elif a.write:
        cr = load(CR_FILE, strict=False) if CR_FILE.exists() else change_request(model)
        plan = simulate(model, cr, [])
        write_report(model, check_plan(plan), plan)


if __name__ == "__main__":
    main()
```

#### Step 3: Generate the Terraform files

1. Run (add `--sample` if you don't have `unit21/calder_account_model.json`):

   ```bash
   python unit21/btp_iac.py --generate
   ```

2. You should see:

   ```text
   Wrote 10 files to unit21/btp-terraform/ for 42 resources:
       3  btp_globalaccount_role_collection_assignment
       4  btp_directory
       1  btp_directory_entitlement
       2  btp_directory_role_collection_assignment
      12  btp_subaccount
      17  btp_subaccount_role_collection_assignment
       3  btp_subaccount_entitlement
       4  import blocks for subaccounts that already exist
       4  production subaccounts with prevent_destroy
   ```

3. Open `unit21/btp-terraform/subaccounts.tf`. The production subaccount `Integration Prod` reads:

   ```text
   resource "btp_subaccount" "integration_prod" {
     parent_id    = btp_directory.platform.id
     name         = "Integration Prod"
     subdomain    = "calder-int-prod"
     region       = "us10"
     usage        = "USED_FOR_PRODUCTION"
     beta_enabled = false
     labels       = {
       "Stage"       = ["Prod"]
       "Owner team"  = ["Integration"]
       "Cost object" = ["CP10-910"]
       "Contacts"    = ["btp-platform@calder-pumpworks.example"]
     }

     lifecycle {
       prevent_destroy = true
     }
   }
   ```

4. Look through the other files:

| File | What it holds |
| --- | --- |
| `versions.tf` | Terraform 1.14 or newer, provider `SAP/btp` pinned to 1.28.1 |
| `provider.tf` | The global account subdomain; no credentials |
| `variables.tf`, `terraform.tfvars.example` | The global account, the identity provider's origin key, and personnel numbers mapped to sign-in names |
| `global_account.tf`, `directories.tf`, `subaccounts.tf`, `access.tf` | The resources, generated from the model |
| `imports.tf` | Import blocks for AI Test, AI Prod, Ext Test and Ext Prod, which were created by hand in 2026 (course GUIDs) |
| `.gitignore` | Keeps state, saved plans and `terraform.tfvars` out of Git |

The header of each file says "Edit the model, not this file." People change `calder_account_model.json` and review it; the generator writes the code. That keeps one source of truth, and the earlier topic's `--check` rules still run on the model.

> **Note** Names, subdomains, personnel numbers, e-mail addresses and GUIDs are course values. `aicore` and `extended` are SAP AI Core's technical service and plan names, as used in the [services and bindings topic](https://erpfde.com/topics/btp-services-and-bindings/).

#### Step 4: Simulate the first plan and review it

1. Run:

   ```bash
   python unit21/btp_iac.py --plan create
   python unit21/btp_iac.py --check-plan unit21/tfplan_create.json
   ```

2. You should see:

   ```text
   Wrote unit21/tfplan_create.json. Plan: 4 to import, 38 to create, 0 to update, 0 to replace, 0 to delete.
   Plan: 4 to import, 38 to create, 0 to update, 0 to replace, 0 to delete.
   WARN P04 btp_globalaccount_role_collection_assignment.ga_admin_00100316: create Global Account Administrator for btp.admin1@calder-pumpworks.example: needs the second platform administrator's approval
   WARN P04 btp_globalaccount_role_collection_assignment.ga_admin_00100317: create Global Account Administrator for btp.admin2@calder-pumpworks.example: needs the second platform administrator's approval
   WARN P04 btp_subaccount_role_collection_assignment.ai_prod_admin_00100290: create Subaccount Administrator for enterprise.architect@calder-pumpworks.example: needs the second platform administrator's approval
   WARN P04 btp_subaccount_role_collection_assignment.ai_prod_admin_00100316: create Subaccount Administrator for btp.admin1@calder-pumpworks.example: needs the second platform administrator's approval
   WARN P04 btp_subaccount_role_collection_assignment.ext_prod_admin_00100316: create Subaccount Administrator for btp.admin1@calder-pumpworks.example: needs the second platform administrator's approval
   WARN P04 btp_subaccount_role_collection_assignment.ext_prod_admin_00100317: create Subaccount Administrator for btp.admin2@calder-pumpworks.example: needs the second platform administrator's approval
   0 FAIL, 6 WARN: may be applied after review
   ```

3. Read it. The four existing subaccounts are imported, not created. The warnings are administrator grants on the global account and on the two production subaccounts that already exist. New subaccounts' administrators don't warn: they arrive with a subaccount the reviewer is already approving.

Open `unit21/tfplan_create.json` if you are curious. Each entry under `resource_changes` has an `address`, a `type` and a `change` with `actions`, `before` and `after`, the shape Terraform documents for its JSON plans.

#### Step 5: Review change request CR-0412

On Friday 2026-11-27 a colleague proposes CR-0412, a "tidy-up" with six edits: move Ext Test into the *Platform* directory, rename Integration Prod's subdomain to `calder-integration-prod`, switch on beta features in Augsburg Prod to try a beta service, add `r2r` to AI Dev's `Process` label, make `00100288` an administrator of AI Prod "to debug", and remove the Sandbox because "nobody uses it".

1. Run:

   ```bash
   python unit21/btp_iac.py --plan change
   python unit21/btp_iac.py --check-plan unit21/tfplan_cr0412.json
   ```

2. You should see:

   ```text
   Wrote unit21/calder_account_model_cr0412.json: the model as CR-0412 proposes it.
   Wrote unit21/tfplan_cr0412.json. Plan: 0 to import, 1 to create, 2 to update, 2 to replace, 3 to delete.
   note: btp_subaccount.integration_prod has prevent_destroy: real Terraform stops the plan with an error here
   Plan: 0 to import, 1 to create, 2 to update, 2 to replace, 3 to delete.
   FAIL P01 btp_subaccount.ext_test: replace: deletes it with everything inside, then creates an empty one (changed: parent_id)
   FAIL P01 btp_subaccount.integration_prod: replace: deletes it with everything inside, then creates an empty one (changed: subdomain)
   FAIL P03 btp_subaccount.augsburg_prod: switches on beta features in production; this can't be switched off again
   WARN P02 btp_subaccount.sandbox: deletes a subaccount; confirm with its owner team that it is empty
   WARN P04 btp_subaccount_role_collection_assignment.ai_prod_admin_00100288: create Subaccount Administrator for integration.dev@calder-pumpworks.example: needs the second platform administrator's approval
   3 FAIL, 2 WARN: do not apply
   ```

3. The exit code is 2, which a pipeline reads as "stop". Check it:
   - **Windows (PowerShell):** `echo $LASTEXITCODE`
   - **macOS / Linux:** `echo $?`

What the gate found, and why each matters:

| Finding | What would happen | Right way |
| --- | --- | --- |
| P01 Ext Test | The provider can't move a subaccount, so it deletes Ext Test with its apps and service instances and creates an empty one | Move in the cockpit, then remove from state, change `parent_id` and import again |
| P01 Integration Prod | A subdomain can't change after creation, so the plan replaces the production subaccount. `prevent_destroy` makes real Terraform stop, but only because the block is still there | Keep the subdomain; change the display name if the name is the point |
| P03 Augsburg Prod | Beta features can't be switched off once on, and SAP advises against them in production | Try the beta service in the Sandbox |
| P02 Sandbox | A non-production subaccount and whatever is in it is deleted | Confirm with the owner team; its `Expires` label says 2027-03-31 |
| P04 AI Prod administrator | A developer gets full administration of production | The second administrator decides; the [security model topic](https://erpfde.com/topics/btp-security-model/) would give read access instead |

The AI Dev label change passes without comment. That is the point of a gate: most changes are dull and should flow; a handful must never reach `apply`.

The rules are course rules built on what the provider and Terraform document:

| Rule | Refuses or warns | Based on |
| --- | --- | --- |
| P01 | FAIL on any replacement of a subaccount or directory | Provider: `parent_id`, `subdomain` and `skip_auto_entitlement` force replacement |
| P02 | FAIL on deleting a production subaccount; WARN on others | Provider: force delete and the pending-deletion period |
| P03 | FAIL on switching on beta in production | SAP: beta can't be disabled once enabled |
| P04 | WARN on administrator grants in production or the global account | Course rule: two platform administrators |
| P05 | FAIL on removing the production flag | Course rule: the flag also blocks force deletion |

#### Step 6: Write the deliverable

1. Run:

   ```bash
   python unit21/btp_iac.py --write
   ```

2. You should see `Wrote unit21/btp_terraform_design.md`. Open it: it lists what Terraform owns, the provider and tools, CR-0412's findings, the pipeline gates and an empty decision record with two open questions. You fill those in during the exercise.

> **Note** These plans come from the course stand-in, not from Terraform talking to BTP. They show how the provider's documented behavior turns edits into deletions. Step 7 shows the same gate on a real plan.

#### Step 7 (optional): Run a real plan against your trial

This step creates one directory in your trial global account, checks the real plan with the gate, and deletes the directory again.

1. Install Terraform: open [developer.hashicorp.com/terraform/install](https://developer.hashicorp.com/terraform/install), pick your operating system and follow the steps there. Check it:

   ```bash
   terraform -version
   ```

   You should see `Terraform v1.14` or a later version.

2. Find your trial's global account subdomain: open the BTP cockpit, choose your trial global account, and read **Subdomain** on its overview page.
3. Make a folder `unit21/btp-terraform-trial` and in it a file `main.tf` with:

   ```hcl
   terraform {
     required_version = ">= 1.14.0"
     required_providers {
       btp = {
         source  = "SAP/btp"
         version = "1.28.1"
       }
     }
   }

   variable "globalaccount" {
     type = string
   }

   provider "btp" {
     globalaccount = var.globalaccount
   }

   resource "btp_directory" "ai_and_agents" {
     name   = "AI and agents"
     labels = { "Owner team" = ["AI platform"] }
   }
   ```

4. Put your trial user in environment variables for this terminal only. Use the e-mail and password of your SAP account; the provider can't sign in with SAP Universal ID, and SAP Note 3085908 explains what to do then.
   - **Windows (PowerShell):**

     ```powershell
     $Env:BTP_USERNAME = 'you@example.com'
     $Env:BTP_PASSWORD = 'your-password'
     ```

   - **macOS / Linux:**

     ```bash
     export BTP_USERNAME='you@example.com'
     export BTP_PASSWORD='your-password'
     ```

   > **Warning** Never put the password in `main.tf` or any file in Git. The environment variables disappear when you close the terminal.

5. Initialize, plan, and convert the plan to JSON (replace the subdomain):

   ```bash
   cd unit21/btp-terraform-trial
   terraform init
   terraform plan -var "globalaccount=<your subdomain>" -out tfplan
   terraform show -json tfplan > tfplan.json
   cd ../..
   python unit21/btp_iac.py --check-plan unit21/btp-terraform-trial/tfplan.json
   ```

   `terraform init` downloads the provider and writes `.terraform.lock.hcl`, which records its checksums; commit that file. The gate should print `Plan: 0 to import, 1 to create, ...` and `0 FAIL, 0 WARN`.

6. Apply the saved plan, then look in the cockpit's **Account Explorer** for the new directory:

   ```bash
   cd unit21/btp-terraform-trial
   terraform apply tfplan
   ```

7. Tidy up. Delete the directory again, and delete the saved plans, which can hold sensitive values:

   ```bash
   terraform destroy -var "globalaccount=<your subdomain>"
   ```

   Type `yes` when Terraform asks. Then delete `tfplan` and `tfplan.json`.

> **Note** We tested Steps 1 to 6 in our environment. The Terraform registry and SAP's servers weren't reachable from it, so Step 7 follows the provider's and HashiCorp's documentation and wasn't run against a live trial.

#### What the code does

| Part | What it does |
| --- | --- |
| `PROVIDER_VERSION`, `SERVICE_NAMES` | The pinned provider release; cockpit names mapped to technical service names |
| `EXISTING`, `USERS` | Course GUIDs of the four hand-made subaccounts; personnel numbers to sign-in names |
| `sample_model()` | The reviewed account model, used with `--sample` |
| `change_request()` | CR-0412's six edits, applied to a copy of the model |
| `resources()` | Turns the model into Terraform resources: addresses, attributes, references, protection |
| `hcl_value()`, `hcl_resource()`, `generate()` | Write the `.tf` files, with `prevent_destroy` on production subaccounts and import blocks |
| `REPLACE_ON`, `simulate()` | The course stand-in for `terraform plan`: which attribute changes force a replacement, in Terraform's JSON plan shape |
| `check_plan()` | Rules P01 to P05 on any plan JSON, the simulated one or a real one |
| `write_report()` | The design document with an empty decision record |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on the path, or the virtual environment is off | Turn on `.venv` (Step 1); on macOS or Linux try `python3` |
| `No model file unit21/calder_account_model.json` | You skipped the account model exercise, or you are in the wrong folder | Add `--sample`, or run from `orchestrate-course` |
| `... is production with beta features on` | Your model still has the account model topic's planted error | Run `python unit21/account_model.py --check` and fix the model |
| `--generate` shows other counts | Your model differs from the reviewed one | Compare it with the account model topic's exercise, or use `--sample` |
| `... is not JSON` from `--check-plan` | You gave it the binary `tfplan` file | Run `terraform show -json tfplan > tfplan.json` and check `tfplan.json` |
| Step 7: `terraform` not recognized | Terraform isn't installed or not on the path | Install it from HashiCorp's page and open a new terminal |
| Step 7: `Failed to query available provider packages` | No internet or a company proxy blocks the registry | Set `HTTPS_PROXY` as [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/) explains, or skip Step 7 |
| Step 7: an authentication error | Wrong password, two-factor on, or SAP Universal ID | Check the variables; see SAP Note 3085908 for Universal ID |
| Step 7: a 401 or 403 error | Your user lacks the role for this level | In the trial you are global account administrator; check you used the right subdomain |

### The SAP way

As of November 2026:

- **Terraform Provider for SAP BTP**, `SAP/btp` 1.28.1 (tagged 17 November 2026). Open source under Apache 2.0, documented on the Terraform registry and in its repository, no official SAP support ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/account-administration-using-infrastructure-as-code-8d201e4.md)). OpenTofu works as a drop-in, but the repository says issues are addressed only when they reproduce with Terraform.
- **Terraform exporter for SAP BTP**, `btptf` 2.0.1 (tagged 23 November 2026), for taking over existing directories, subaccounts and Cloud Foundry orgs. Terraform 1.14 or newer; OpenTofu not supported; no official SAP support.
- **Cloud Foundry provider** `cloudfoundry/cloudfoundry` (1.19.0) for orgs, spaces, apps and space roles inside an environment instance the BTP provider created.
- **Scripting and Automation Preview** in the cockpit, showing Terraform blocks for the page you are on. Useful for learning the resource names.
- **Samples**: SAP-samples' `btp-terraform-samples` and the administrator guide's samples, linked from SAP's documentation.
- **Licensing:** the provider, exporter and Terraform CLI are free to download. What Terraform creates is billed as usual, and a force-deleted subaccount can still cost money during its pending-deletion period.

### Build vs. SAP

| Need | SAP provides | You build | Why |
| --- | --- | --- | --- |
| Talk to BTP from Terraform | The provider | Nothing | Don't write your own API scripts for what the provider covers |
| Take over a hand-built landscape | The exporter | A review of its generated code | The exporter writes everything, including defaulted optional values |
| One source of truth for the model | Nothing specific | A model file and generator, or hand-written modules | Your account model, rules and owners are yours |
| Refuse dangerous plans | Terraform's `prevent_destroy`; the provider's guide suggests policy checks on the plan | The gate (P01 to P05), or a policy tool such as Open Policy Agent | Only you know which deletions are never acceptable |
| Run it | Nothing specific | A pipeline, remote state, a technical user | Fits the company's existing CI and secret store |

### Architecture view

**Where it sits.** Terraform runs in Calder's CI pipeline, outside BTP. It reaches the BTP account APIs through the provider and the btp CLI server. State lives in an encrypted object store the company already runs, with locking. Nothing in S/4HANA is touched: connections to `S4D`, `S4Q` and `S4P` stay in the [connectivity design](https://erpfde.com/topics/btp-connectivity/).

```mermaid
flowchart LR
  Dev[Change in Git] --> CI[CI pipeline<br/>technical user, X.509]
  CI --> Gate[Plan gate]
  Gate --> API[BTP account APIs<br/>via provider]
  CI <--> St[(Remote state<br/>encrypted, locked)]
  API --> GA[Global account<br/>4 directories, 12 subaccounts]
  IdP[Cloud Identity Services<br/>calder-platform] --> CI
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Safety | No replace or delete of production without two named approvals | One merged edit empties a production subaccount |
| Confidentiality of state | Encrypted at rest, read only by the pipeline and the platform team | Secrets in state leak to anyone with storage access |
| Consistency | State locking; one pipeline run at a time per state | Two runs overwrite each other's state |
| Recoverability | State versioned; break-glass access outside the pipeline | A corrupted state or bad apply locks everyone out |
| Drift | Weekly refresh-only plan, tickets on exit code 2 | Cockpit changes pile up unseen |

**Integration and identity.** The pipeline signs in as a technical user from Calder's SAP Cloud Identity Services tenant with an X.509 certificate held in the CI secret store. It becomes administrator of every subaccount it creates, so its rights equal the platform team's. People never apply from laptops to production. The administrator assignments it writes use the `calder-platform` origin from the [security model](https://erpfde.com/topics/btp-security-model/).

**The decision to record.**

- **Context:** twelve subaccounts in four directories, four built by hand, one platform team, a second team (AI platform) administering its own directory.
- **Options:** (A) one state for the whole global account; (B) one state for the global account and directories plus one per workload directory; (C) one state per stage across all workloads.
- **Decision:** A now, B when the AI platform team runs its own pipeline. A keeps 42 resources reviewable by one team; B limits a bad apply to one workload; C splits a subaccount's directory from its siblings for no gain.
- **Consequences:** every change needs a platform administrator's approval until B; the migration to B is a state move that must be planned like any other change.

**What a design review will ask.**

1. Who approves a plan that touches production, and how is it enforced?
2. Where does state live, who can read it, and how is it backed up and locked?
3. Which resources are still managed by hand, and how is their drift found?
4. What happens if the pipeline's credential leaks?
5. Who supports the provider when a release breaks the pipeline?

### Production concerns

- **Security and authorizations.** The technical user is the most privileged identity in BTP; give it a certificate, not a password, and review its sign-ins. Drift checks need a viewer role in each subaccount since provider 1.26.0. Keep the break-glass user out of code.
- **Pin and verify.** Pin the provider version and commit `.terraform.lock.hcl` with its checksums, as the [AI supply-chain controls topic](https://erpfde.com/topics/ai-supply-chain-controls/) does for Python packages. Upgrade on purpose, reading the release notes.
- **State.** Encrypted, versioned, locked, never in Git. Saved plans in JSON hold sensitive values too; delete them after the run.
- **Evaluation of the gate.** Keep a set of known-bad plans (CR-0412 is one) and run them against the gate in CI, so a change to the rules can't silently weaken it.
- **Cost.** Terraform creates billable things quickly. Labels for cost objects belong in the model, and a deleted subaccount can still bill during pending deletion. [BTP commercial models and cost control](https://erpfde.com/topics/btp-commercial-models-and-cost/) covers how those labels feed cost reports.
- **Operations.** Plan on every pull request, apply only from the main branch, refresh-only drift check weekly. Record who approved each apply.
- **Clean core.** Terraform manages BTP, not S/4HANA; it keeps extensions in their own subaccounts, which is what a clean core design needs.

### Where AI fits

AI changes two things here. First, coding assistants draft HCL quickly, and SAP's [MCP server for BTP administration](https://erpfde.com/topics/btp-account-model/) lets an agent act on accounts directly. An agent that drafts code for review fits this design; an agent that applies does not. It operates with its user's full scope, so give it a plan to propose, never an apply to run.

Second, a model can explain a large plan in plain words for the approver. Treat that as a summary beside the gate, never instead of it: the gate's rules are deterministic, and a fluent summary of "2 to replace" is still two deletions. For how agents get approved tools and limited rights, see [registering and approving MCP servers](https://erpfde.com/topics/registering-and-approving-mcp-servers-in-ai-agent-hub/).

### Pitfalls

- **Editing `parent_id` to move a subaccount.** It deletes and recreates. Move in the cockpit, then state removal and import.
- **Changing a subdomain in code.** It can't change after creation; the plan replaces the subaccount.
- **Trusting `prevent_destroy` alone.** It doesn't help when the resource block is deleted.
- **Applying without reading the plan.** `apply` without a saved plan computes a fresh one; apply the reviewed `tfplan` file instead.
- **State in Git.** It holds sensitive values in plain text.
- **Letting someone click in the cockpit after the switch.** The next plan reverts their change, or shows drift nobody owns. Agree what stays manual.
- **Setting `amount` on a plan without numeric quota.** The provider rejects it; check the plan's category first with the entitlement data sources.
- **Forgetting the creator rule.** The pipeline's technical user becomes administrator of every subaccount it creates.
- **Running the exporter's output unread.** It includes every defaulted optional attribute; remove what you don't want to pin, then import.

### Exercise

Fix CR-0412 so it can be applied, add one rule to the gate, and record the decision.

1. Open `unit21/calder_account_model_cr0412.json` in VS Code.
2. In the node `"name": "Ext Test"`, change `"parent": "Platform"` back to `"parent": "Extensions"`. The move, if still wanted, is done in the cockpit first.
3. In `"name": "Integration Prod"`, change `"subdomain": "calder-integration-prod"` back to `"subdomain": "calder-int-prod"`.
4. In `"name": "Augsburg Prod"`, change `"beta_enabled": true` to `"beta_enabled": false`.
5. Run the plan and the gate again. Without `--force`, `--plan change` keeps your edited file:

   ```bash
   python unit21/btp_iac.py --plan change
   python unit21/btp_iac.py --check-plan unit21/tfplan_cr0412.json
   ```

   It should end with `0 FAIL, 2 WARN: may be applied after review` and the plan `0 to import, 1 to create, 1 to update, 0 to replace, 3 to delete.`

6. Add rule P06, Calder's course rule that subaccounts live only in `us10` or `eu10`. In `unit21/btp_iac.py`, add this line just above `ADMIN_ROLES = {`:

   ```python
   ALLOWED_REGIONS = {"us10", "eu10"}   # course rule P06
   ```

7. In `check_plan()`, find the line that adds `"P05"`. Directly after it, at the same indentation as the `if` above it, paste:

   ```python
           if rtype == "btp_subaccount" and after and after.get("region") not in ALLOWED_REGIONS:
               add("FAIL", "P06", addr, f"region {after.get('region')} is not one of Calder's regions "
                   f"({', '.join(sorted(ALLOWED_REGIONS))})")
   ```

8. Test the rule: in the CR file, add a subaccount after the last node (type a comma after its closing `}` first):

   ```json
   {"type": "subaccount", "name": "AI Lab", "parent": "AI and agents", "stage": "dev",
    "region": "ap10", "subdomain": "calder-ai-lab", "used_for_production": false,
    "beta_enabled": false, "admins": ["00100288"], "labels": {"Stage": ["Dev"]},
    "entitlements": {}}
   ```

9. Run Step 5's two commands again. You should see `FAIL P06 btp_subaccount.ai_lab: region ap10 is not one of Calder's regions (eu10, us10)` and `1 FAIL, 2 WARN`. Remove the AI Lab node and run them once more to get back to `0 FAIL`.
10. Run `python unit21/btp_iac.py --write`, open `unit21/btp_terraform_design.md`, and fill in the decision record (state layout A, B or C, in your own words) and answer both open questions.
11. Commit the script, the model files, `unit21/btp-terraform/` and the design document with Git. The `.gitignore` there keeps state and `terraform.tfvars` out.

**Done when:** the gate reports `0 FAIL, 2 WARN` for your fixed CR-0412 with exit code 0, rule P06 fails the `ap10` test subaccount, and `unit21/btp_terraform_design.md` has a filled-in decision record and answers to both open questions. Keep it: the Architect capstone (Unit 32) collects it into Calder's platform operating model.

### Check yourself

1. In Terraform's model, why can't a plan show drift on a subaccount that an administrator created in the cockpit last month and nobody imported?
   - A. The provider reads subaccounts only in the global account's default region
   - B. It is in neither state nor configuration, so Terraform never compares it
   - C. Drift detection in the provider covers directories but never subaccounts
   - D. The cockpit marks subaccounts made by hand as read-only for every API

   Answer: B. Terraform compares configuration, state and reality only for objects it created or imported. The provider's drift guide says resources created manually and not in state are invisible to it. Importing, or SAP's exporter, fixes that.

2. A change edits `subdomain` on the production subaccount Integration Prod, which carries `prevent_destroy = true`. What does real Terraform do at plan time?
   - A. Renames the subdomain in place, because only one attribute changes
   - B. Replaces the subaccount, after asking the operator to type yes twice
   - C. Stops with an error: the plan would destroy a protected object
   - D. Skips the change silently, because subdomains are read-only fields

   Answer: C. A subdomain can't change after creation, so the plan needs a replacement, which destroys the old subaccount. `prevent_destroy` rejects any plan that destroys the protected object. It would not help if the whole block were deleted instead.

3. Which plan entry should the course gate's rule P01 treat as a replacement?
   - A. `"actions": ["update"]` on a `btp_subaccount` whose labels changed
   - B. `"actions": ["delete", "create"]` on a `btp_subaccount`
   - C. `"actions": ["no-op"]` on a `btp_subaccount` with an `importing` block
   - D. `"actions": ["create"]` on a new subaccount role collection assignment

   Answer: B. Terraform's JSON plan shows a replacement as the pair delete and create, in either order. An update keeps the object, a no-op with importing takes over an existing one, and a create adds something new.

4. Calder's pipeline must sign in to BTP without a person present. Which provider authentication fits best?
   - A. The btp CLI session, started with `btp login --sso` on the build agent
   - B. A named administrator's password, with two-factor authentication on
   - C. A personal SAP Universal ID, stored in two environment variables
   - D. A technical user with an X.509 certificate from Calder's identity provider

   Answer: D. The provider documents X.509 and JWT assertion for custom identity providers; the btp CLI session isn't supported in CI/CD. User and password works neither with two-factor authentication nor with SAP Universal ID.

5. Ext Test must move into the Platform directory without losing its apps. What is the safe sequence?
   - A. Change `parent_id` in the code and apply the plan during a quiet hour
   - B. Move it in the cockpit, drop it from state, fix `parent_id`, import it
   - C. Delete it with Terraform, then bring it back with `btp_restore_subaccount`
   - D. Export it with btptf into the new directory and apply the exported code

   Answer: B. The provider can't move subaccounts; changing `parent_id` deletes and recreates. Its guide's workaround moves the subaccount outside Terraform, then updates state and code. A restore brings back a deleted subaccount, it doesn't move one.

6. Why does the pipeline's technical user need the same protection as a platform administrator?
   - A. SAP requires every technical user to hold the Global Account Viewer role
   - B. Terraform writes the technical user's password into each `.tf` file
   - C. Whoever creates a subaccount is made its administrator automatically
   - D. The provider shares one session among all users of the global account

   Answer: C. SAP's documentation says the creator of a subaccount is automatically assigned as its administrator. A pipeline that creates every subaccount therefore administers all of them, so its certificate and sign-ins need the strictest controls.

7. The weekly drift job runs `terraform plan -refresh-only -detailed-exitcode` and ends with exit code 2. What does that mean?
   - A. The plan failed with an authorization error in one of the subaccounts
   - B. Reality differs from state, so someone should review the changes
   - C. Nothing changed, and the landscape still matches the code exactly
   - D. Another pipeline run holds the lock on the state file right now

   Answer: B. With `-detailed-exitcode`, 0 means no changes, 1 an error and 2 that changes are present. On a refresh-only plan, changes mean drift, which needs an owner. An authorization error would return 1.

8. Where should Calder keep Terraform's state for the BTP landscape?
   - A. In the Git repository next to the `.tf` files, so reviewers see it
   - B. In the Sandbox subaccount, since it holds no production data at all
   - C. On each administrator's laptop, so no single store can fail them all
   - D. In encrypted, locked, versioned storage read only by the pipeline

   Answer: D. The state stores sensitive values in plain text and is what the next plan compares against. It needs encryption, locking against parallel runs and versions for recovery. Git and laptops expose it or let copies diverge.

## Sources

- [Account Administration Using Infrastructure as Code (SAP BTP documentation, SAP-docs on GitHub, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/account-administration-using-infrastructure-as-code-8d201e4.md): the Terraform Provider for SAP BTP is open source under Apache 2.0 with no official SAP support; it manages subaccounts, directories, entitlements, environment instances, subscriptions, service instances and bindings, users and role collections, trust to custom identity providers; registry, repository, tutorial and samples
- [Terraform Provider for SAP BTP: repository, provider documentation and guides (GitHub, release v1.28.1 tagged 2026-11-17, read 2026-11-27)](https://github.com/SAP/terraform-provider-btp): provider source SAP/btp; authentication by user and password (not with SAP Universal ID, no two-factor), X.509, JWT assertion with a custom IdP, or the btp CLI session (not in CI/CD); OpenTofu as a drop-in with issues addressed only if reproducible with Terraform; resource and data source list; actions add_me_as_subaccount_admin and restore_subaccount
- [btp_subaccount resource (Terraform Provider for SAP BTP documentation)](https://github.com/SAP/terraform-provider-btp/blob/main/docs/resources/subaccount.md): name, region, subdomain required; subdomain can't change after creation; usage values USED_FOR_PRODUCTION and NOT_USED_FOR_PRODUCTION; parent_id change deletes and recreates; skip_auto_entitlement changes need replacement; failed delete retried as force delete with a pending deletion period of several days, only if force deletion is enabled and the subaccount isn't marked for production; the subaccount leaves the state while pending deletion
- [Drift Detection and Limitation: Move of Subaccounts (Terraform Provider for SAP BTP guides)](https://github.com/SAP/terraform-provider-btp/blob/main/guides/DRIFTDETECTION.md): drift visible only for resources created by or imported into Terraform; plan -refresh-only and -detailed-exitcode; since v1.26.0 role collection assignments are read back and need a read role such as Subaccount Viewer; service instance parameters not tracked; the move guide gives the cockpit move, state removal and import workaround
- [Accessing sensitive data in local executions (Terraform Provider for SAP BTP guides)](https://github.com/SAP/terraform-provider-btp/blob/main/guides/SENSITIVEDATA.md): sensitive fields are hidden in CLI output but stored in plain text in the state file, which belongs in encrypted storage; plan JSON files contain sensitive values and must stay out of source control
- [Terraform Exporter for SAP BTP (btptf CLI) documentation (release v2.0.1 tagged 2026-11-23, read 2026-11-27)](https://sap.github.io/terraform-exporter-btp/): exports directories, subaccounts and Cloud Foundry orgs as Terraform code with import blocks; version 2 uses list resources and needs Terraform CLI 1.14 or newer, OpenTofu not supported; JSON inventory workflow; writes no state file so a remote backend can be added first; no official SAP support
- [Tools for Account Administration (SAP BTP Administrator's Guide, SAP-docs on GitHub)](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/tools-for-account-administration-6bdb3a7.md): Terraform provider for scalable, repeatable subaccount provisioning; learning curve; align with Terraform or OpenTofu where the company already uses it for other clouds
- [Scripting and Automation Preview (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/scripting-and-automation-preview-7cf9f14.md): a cockpit panel that shows btp CLI, cf CLI and Terraform equivalents of the current page; needs Terraform with the SAP BTP and Cloud Foundry providers for the Terraform tab
- [Create a Subaccount (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/create-a-subaccount-05280a1.md): whoever creates a subaccount is automatically assigned to it as an administrator
- [Terraform documentation: JSON output format, lifecycle meta-argument and terraform plan (HashiCorp, v1.14.x docs, read 2026-11-27)](https://developer.hashicorp.com/terraform/internals/json-format): resource_changes with address, actions (no-op, create, update, delete, delete then create), before, after, action_reason and importing; prevent_destroy rejects plans that destroy the object but not when its configuration is removed; plan -detailed-exitcode returns 0, 1 or 2
