Inventory Existing Console, ROS and Terraform Ownership
An ownership register is the first artifact, not the HCL. Every VPC, vSwitch, security group and bucket already has a declarer: a ROS stack, a console habit, a shell script, another root, or nobody. Import is a transfer between declarers, so the register names the current one before any resource block exists.
ROS is a declarer with delete rights. A stack owns the resources its template creates, and a resource removed from the template is deleted on the next update unless its deletion policy says retain. Deletion protection guards the stack itself, not the objects inside it, so a protected stack can still lose a vSwitch when the template stops declaring it. Read the template and the stack's resource list before concluding that an object is unmanaged.
A stack policy is the guard that names resources. It can deny the update that would delete or replace a listed resource, while deletion protection only blocks deleting the stack. Read the policy before assuming the template is safe to edit, and record the stack's parameters with the resource list as part of the evidence.
ROS can also adopt resources, which makes the ambiguity worse. The service can build a template from an existing resource group and import those resources into a stack, with a deletion policy of retain. After that import, ROS is the declarer even though no human wrote the template line by line. The stack's resource list is the evidence, not the existence of a template file in a repository.
The console and the CLI are owners with no record. A resource created by hand has no manifest and no state address, and ActionTrail shows the principal that called the create API rather than the team expected to maintain the result. Treat console ownership as a decision to adopt or tolerate, never as evidence that nobody owns the object.
Terraform proves ownership through state. The address, the backend key and the workspace identify one declarer for one object. A matching tag proves nothing, because anyone with write access can set or copy it. Two roots that declare the same identifier both plan cleanly and take turns undoing each other.
Administrative bootstrap belongs in the register too. The state bucket, the Tablestore lock table and the CI roles exist before the workload root can plan. Record them as bootstrap-owned, name the human or platform root that maintains them, and keep them out of the workload import set.
Some objects should never be imported. Account-wide controls such as the ActionTrail trail, the RAM password policy and resource directory settings belong to every workload at once. Shared network objects such as a shared vSwitch, a CEN instance or a transit router belong to the account that owns them, and a participant root should read them rather than adopt them. A transfer the owner did not approve is an outage waiting for a review.
A handover needs a window with zero declarers. Either the old owner stops writing first, or the new root imports while the old owner is paused; an overlap produces two clean plans and two writers. Put that window in the register next to the approver, because it is the only part of the transfer that needs a calendar.
Reads disagree, so collect more than one. Resource Center search is fast but sees only indexed resource types; Cloud Config has configuration history but lags; ActionTrail sees the call, not the intent; a stack resource list sees one stack. The register is trustworthy when two of those reads agree on the identifier and the declarer.
Bound the set before writing anything. One region, one VPC, ten to twenty objects, and nothing whose replacement loses data. A bounded import is reviewable in one sitting; an account-wide sweep produces a plan nobody reads and a rollback nobody can execute.
The register has fixed columns. Canonical identifier, current declarer, the evidence that proves it, the target address and provider alias, the companion objects, the transfer window and the approver. Table 1 sorts the readable signals by what each one can actually prove.
| Signal | What it proves | Blind spot |
|---|---|---|
| ROS stack resource list | This stack currently records these physical IDs | Says nothing about resources dropped from an earlier template |
| Terraform state address | This backend and prefix record this identifier | One root per read; other roots stay invisible |
| Resource Center search | The object exists in this account and region | No declarer, uneven type coverage, and indexing lag |
| Cloud Config history | The object's configuration changed at these times | Records the change, not the owner |
| ActionTrail event | This principal made this call | Records the action, not the intent or the maintainer |
| Tags | Someone chose these values | Any writer can change or copy them |
Figure 1 turns that evidence into one decision per object.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Object exists in one region"] --> B{"Which record names the declarer?"}
B -->|"stack resource list"| C["ROS stack"]
B -->|"state address"| D["Terraform root"]
B -->|"audit event only"| E["Console, CLI or script"]
B -->|"nothing"| F["Unrecorded or orphan"]
C --> G{"Deletion policy is Retain?"}
G -->|"no"| H["Retain it in the template first"]
G -->|"yes"| I["Remove it from the stack, then adopt"]
D --> J{"Same backend, prefix and alias?"}
J -->|"yes"| K["Change it where it lives"]
J -->|"no"| L["Transfer through zero declarers"]
E --> M["Name an owner, then adopt or delete"]
F --> N["Do not import yet"]
H --> I
I --> O["Register canonical ID, declarer and evidence"]
K --> O
L --> O
M --> O
N --> O
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,G,J primary;
class C,D,E secondary;
class I,K,L,M,O ok;
class H warn;
class F,N danger;
Figure 2 places the three declarers and the two shared boundaries on one canvas, because the boundary matters more than the inventory count.
The register is finished when two readers agree. One reads the evidence and names the declarer; the other reads the target address and predicts what the first plan will propose. If they disagree, the object is not ready for import and the next section starts with a smaller set.
Import a Supported Object and Reach a Stable Plan
The canonical identifier is the API's own ID, not the console label. A console page shows a name, a public address and an ID, and only the last one is what the provider records in state. Import fails on a label that looks unique but is not the identifier the API accepts.
Import support is per resource and per provider release. The resource page has an Import section that names the identifier shape, written for the release you pinned. Read that section for 2.2.0 rather than the version you remember, because a resource can gain import support and a composite ID can change its separators between releases. A resource with no import path stays external or is adopted by hand.
Three identifier families cover most of the estate. Simple IDs begin with a product prefix such as vpc- or i-, names are the identifier for a few global collections, and composite IDs join several fields with colons. Pasting the display name into the first family and the ARN into the second are the two most common import errors.
OSS is the exception that punishes a guess. The bucket name is the identifier and it is globally unique across all Alibaba Cloud accounts. A URL or an oss:// prefix is not an identifier, and a name already held by another account cannot be adopted at all. That is a naming collision, not a missing permission.
RAM and KMS identifiers are names and IDs, not ARNs. A RAM role is imported by role name and a KMS key by its key ID, while the alias is a separate object with its own address. Pasting an ARN adds an account ID that the import does not expect, and the resulting error usually reads as not found.
An import block is a reviewable change. Terraform 1.17.1 accepts an import block that names the destination address and the identifier in configuration, so the adoption appears in the diff like any other edit. The older command-line import still works for one object, but it mutates state and leaves no artifact for a reviewer to read afterwards.
Generated configuration is a draft, not a resource. Generated HCL describes the live API rather than your naming or module conventions, and it can write literal secret values into a file. Read it line by line, move sensitive arguments to references, and treat every generated argument as unconfirmed until a plan agrees with it.
Import at the final address. A temporary address followed by a move doubles the review and leaves an intermediate state other tooling can observe. Decide the module path and resource name first, then confirm that address appears exactly once in the plan.
Use a move block when the address changes, not a second import. Terraform 1.17.1 records an address change in configuration and the provider keeps the same object, so the plan shows a move rather than a destroy and create. A move across resource types only works when the provider declares it; a rejected move means the object needs an import window instead.
Inspect the stored identifier before trusting the plan. A state view prints the identifier exactly as recorded, and the product's describe call prints the canonical form the API uses. A one-segment difference means you imported a different object; a case-only difference means the configuration, not the object, needs fixing.
Companions must travel with the object. A security group without its rules, a RAM role without its policy attachment, or a bucket without its ACL and policy is half-owned: the next plan proposes the missing piece and the create collides with a setting that already exists. When a companion belongs to the platform root, record it as external instead of importing it here.
A successful import is not a clean plan. Import records the object, then the next plan compares configuration with the live API. The default resource group, an empty tag map, a description the console wrote, and billing attributes the API reports but the configuration omits all appear as a diff. Some of those are stable differences you encode rather than argue with.
The baseline is an empty plan with named exceptions. Every remaining diff needs an owner, a reason and a comment, and a diff that another system writes belongs in an ignore rule rather than a permanent argument. Anything you cannot explain in one sentence is not a baseline yet.
Table 2 gives the identifier shapes an importer actually meets.
| Resource | Import identifier | Common mistake |
|---|---|---|
| VPC | vpc- ID | Using the VPC name |
| VSwitch | vsw- ID | Pasting the VPC ID |
| Security group | sg- ID | Importing the rule set instead of the group |
| ECS instance | i- ID | Using the instance name |
| EIP address | eip- ID | Using the public IP address |
| SLB instance | lb- ID | Using the load balancer name |
| OSS bucket | Bucket name | Pasting a URL or an oss:// prefix |
| RAM role | Role name | Pasting the role ARN |
| KMS key | Key ID | Using the alias instead of the key |
| RAM role policy attachment | role:<policy>:<type>:<role> | Guessing the separators |
Figure 3 traces the loop and the five ways a plan can answer back.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Bound the set: one region, one VPC, 10 to 20 objects"] --> B["Read the Import section for 2.2.0"]
B --> C{"Import documented?"}
C -->|"no"| C1["Reference it or adopt by hand"]
C -->|"yes"| D["Write the block at its final address"]
D --> E["Import block names the canonical ID"]
E --> F["terraform plan"]
F --> G{"Answer for the imported address"}
G -->|"not found"| G1["Wrong region, identifier or account"]
G -->|"already managed"| G2["Another address or another root"]
G -->|"replacement"| G3["Immutable field or schema disagrees"]
G -->|"in-place diff"| G4["Default or server normalisation"]
G -->|"no changes"| H["Apply once, then remove the import block"]
G1 --> B
G2 --> C1
G3 --> D
G4 --> D
H --> I["Baseline: empty plan on the next run"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,E,F,H primary;
class B,C,D secondary;
class G,I ok;
class C1,G1,G3 danger;
class G2,G4 warn;
Sort the answers before changing anything. A not-found is a reading error, an already-managed answer is an ownership error, a replacement is a schema error, and an in-place diff is an encoding error. Each one has a different fix, and only the last one is usually safe to accept as a diff you will keep.
A failed import is cheaper than a duplicate create. Import writes state and never changes the account. If the plan after import proposes a replacement, the object was not what you thought it was, and stopping there costs one review cycle instead of an outage.
A replacement after import is a stop signal, not a diff to approve. It means the configuration and the live schema disagree about an immutable argument, and applying it destroys the object you just adopted. Read the argument named in the replacement before changing the object, because the import proved the object exists, not that the block describes it.
Review Deprecations, Quotas and Regional Endpoints
Pin both versions before reading any changelog. Terraform 1.17.1 and provider 2.2.0 belong in the configuration, and the lock file records what init actually downloaded. A range such as a floating minimum resolves a different binary next month, which turns a schema review into guesswork.
A major version changes shapes, not only field names. In 2.0 the Container Service runtime argument became a block, and the cluster certificate and connection attributes changed from maps to lists. These failures appear at validation or plan time, before the first API call, which is the cheapest place to meet them.
References follow the shape. Outputs that indexed by key now use list positions, and the database instance class data source changed its storage range the same way. Rewrite every reference in one pass, then confirm the plan contains no address changes you did not intend.
The installed schema is the local evidence. After init, the provider schema command prints every resource, argument, block and deprecation marker the binary knows. Compare that output with the configuration before the first plan against an account, because a field that the changelog calls deprecated still validates today.
Read deprecations as a queue, not a crisis. Pick one family per release, replace it, and confirm the plan is empty before the next family. A sweep that changes names, splits inline blocks and moves resources in one commit produces a plan nobody can attribute to a cause.
Deprecated fields still work in 2.2.0, which is exactly the risk. The VPC resource still accepts its old name argument, still accepts the misspelled router table argument, and still accepts inline secondary CIDR blocks. Each one has a documented replacement, and each one can disappear at a release boundary nobody scheduled.
Table 3 pairs each deprecated field with its replacement and the plan symptom to expect while both exist.
| Deprecated field or resource | Replacement | What the plan shows if both exist |
|---|---|---|
alicloud_vpc.name | vpc_name | Two arguments for one name, and a permanent diff |
alicloud_vpc.router_table_id | route_table_id | The same value recorded under two names |
alicloud_vpc.secondary_cidr_blocks | alicloud_vpc_ipv4_cidr_block | Inline block and companion resource fighting |
alicloud_oss_bucket.acl | alicloud_oss_bucket_acl | Two writers for one ACL |
alicloud_oss_bucket.policy | alicloud_oss_bucket_policy | Two writers for one bucket policy |
alicloud_slb | alicloud_slb_load_balancer | Unknown type, or a move the provider rejects |
alicloud_slb_attachment | alicloud_slb_backend_server | The same attachment under two addresses |
alicloud_ram_policy.document and .name | policy_document and policy_name | Validation error once the old fields are removed |
alicloud_ram_role.document and .name | assume_role_policy_document and role_name | Validation error once the old fields are removed |
Splitting an inline block changes addresses. The deprecated argument and its replacement are different resources, so the plan proposes a create unless you import the companion. Do it in one change: import the companion, remove the inline argument, and confirm the plan destroys nothing.
A removal is a separate release from a rename. A rename keeps the object and changes the argument; a removal deletes the old field and may delete the companion resource. Schedule them apart so the plan after each step has one explanation.
State has a schema version too. Back up the state object before the first plan on a new provider, and keep bucket versioning on so the backup is a version rather than a hope. Init and plan upgrade the state schema in memory, while apply writes it, and an older provider can then refuse a state it no longer understands.
Quotas are regional, per service and sometimes per account. Compute quota is counted per instance family in a region, while VPC, EIP and SLB limits are counted per region and account. Security group rules have a per-group ceiling, and RAM roles, policies and OSS buckets have account-level ceilings. Quota Center is the place to read the current number and file the increase, and the number on the page is the one that applies to your account tier.
Capacity is not quota. A quota says how many instances you may create; capacity says whether the zone has stock of the family you chose. An instance type that is available in one zone can be sold out in another, and a retry in a different zone is a design change rather than a retry. Read zone availability before promising a launch date.
Endpoints decide which API answers. RAM and STS are reached through global endpoints, while VPC, ECS, RDS, OSS, SLB and KMS are regional. The endpoint override block is a deliberate exception, and an override that disagrees with the provider region sends the request to the wrong place. An OSS bucket's region is fixed when it is created, so a later move is a new bucket and a data migration.
Activation is a third gate. A product that was never activated returns an error that reads like a permission problem, and a service-linked role may need to exist before the first resource can be created. Read the message before widening the policy, and record the activation step beside the resource that needs it.
Record the findings next to the version. The change record for an upgrade names the target Terraform and provider versions, the deprecated fields and their replacements, the quota increases requested, the capacity choice and the endpoint scope. That is the evidence a reviewer needs to approve the plan, and it is also the checklist for the next upgrade.
Table 4 sorts the change classes a first plan after an upgrade tends to contain.
| Change class | Plan symptom | Review action |
|---|---|---|
| Deprecated field replaced | In-place update, or a create for a companion | Import the companion, then remove the old argument |
| Removed field or resource | Validation error, or unknown resource type | Move when supported, otherwise import in a window |
| Attribute type changed | Invalid index or unsupported attribute at plan | Rewrite the reference, then confirm no replacement |
| Provider default changed | In-place update with no configuration edit | Encode the old value, or accept and record it |
| State schema bumped | Older provider refuses the state file | Back up first, upgrade forward, never roll back blind |
| Endpoint override stale | Not found or wrong-region data | Remove the override or align it with the region |
Table 5 pairs the constraint with where it is actually enforced.
| Constraint | Scope | Where to confirm | Planning response |
|---|---|---|---|
| vCPU quota | Region and instance family | Quota Center | Request an increase or change family |
| VPC and vSwitch count | Region and account | Quota Center | Reuse a VPC before creating another |
| EIP and SLB count | Region and account | Quota Center | Release idle objects first |
| Security group rules | Security group | The group's rule list | Split groups by purpose |
| RAM roles and policies | Account | RAM console and Quota Center | Remove stale attachments |
| OSS bucket count | Account | OSS console and Quota Center | Reuse buckets with prefixes |
| Zone capacity | Zone and instance family | Zone and instance type data | Choose another zone deliberately |
A quota increase is a change with a lead time. File it before the apply window, record the ticket or request ID, and do not treat an approved quota as capacity. The approval raises the ceiling; the zone still has to have the stock.
Use Scoped Short-Lived CI Credentials and Protected Plans
Federation removes the stored key. A workload presents a short-lived OIDC token, assumes a RAM role, and receives an STS credential for a bounded session. Nothing long-lived is stored in the pipeline, and deleting the OIDC provider or the role trust is the off switch.
The trust policy is the real authorization boundary. It names the OIDC provider and the claims that identify the repository, branch or environment allowed to assume the role. A token from another repository is refused even if the workflow file is copied, because the claim does not match. Keep the audience and subject conditions narrow enough that a fork cannot inherit the role.
The token should be a file, not an inline value. The provider re-reads a token file and re-assumes the role before the session expires, while an inline token is exchanged once at configuration time. A long apply can outlive a short session, and the failure arrives in the middle of the graph rather than at the start.
Plan and apply should not share an identity. The plan role reads the target account and the state object; the apply role writes resources and state and holds only the service-level actions the change needs. A pull-request plan then cannot change infrastructure even if someone edits the workflow file. The same split makes a denial during plan a policy finding rather than an apply incident.
Prove the split with a denied write. Run the plan role against a scratch change that would create a resource and confirm the denial arrives before any state write. A role that can plan and apply is one compromised workflow away from an incident, and the proof is a failed call, not a policy document.
The state backend is part of the trust boundary. State holds identifiers, outputs and often sensitive values, so the OSS bucket needs versioning, encryption, a public access block and one prefix per root. Locking uses a Tablestore table; a backend without one serialises nothing, and two applies can interleave writes that neither plan predicted.
The saved plan is the approval unit. Write the plan to a file, render its JSON, hash both, and keep them with short retention. Approvers approve that hash, and the apply job downloads exactly that artifact. A workflow that re-plans after approval has approved a different change.
Retention is part of the control. Keep the plan, its JSON and the hash for the life of the change record, then delete them on a schedule. A plan artifact contains resource attributes and sometimes sensitive values, so it belongs in the same access boundary as state, not in a public build log.
A saved plan is bound to the state it was made from. If another run writes the prefix between plan and apply, the saved plan is stale even though the commit has not moved. Terraform refuses the apply, and that refusal is a control: plan again from the same commit instead of forcing the file through.
Serialise per state prefix and never cancel an apply. A concurrency group keyed on the prefix lets one run finish before the next starts, and cancel-in-progress turns a slow apply into a partial one. A held lock is a queue signal, not a reason to force-unlock.
Record four coordinates for every promotion. The account and region the plan resolved, the identity that applied, the source commit with the lock file hash, and the digest of the plan that was approved. If the configuration references an application artifact, add its digest too, because a tag is not a version.
A scheduled read-only plan is the drift alarm. Run it with the plan role, treat exit code two as changes exist, and route the result to the owner instead of auto-applying. The same run proves the federation still works after a credential or binding change.
Write the exceptions into the change record. An imported object, an external data source and a bootstrap-owned trail are all deliberate exceptions to the rule that one root owns one object. The reviewer who approves the plan is also approving that list.
Table 6 pairs each control with what it actually stops.
| Control | What it stops | Evidence to keep |
|---|---|---|
| OIDC role with claim conditions | A copied workflow using another repository's token | Issuer, subject and audience in the trust policy |
| Separate plan and apply roles | A pull request that can write infrastructure | Role ARNs and the denied write during plan |
| Saved plan and hash | Approval of a change that was never reviewed | Plan file, JSON and SHA-256 |
| Prefix queue and lock table | Two applies interleaving writes | Lock ID and queue timestamp |
| No cancel in progress | A slow apply becoming a partial one | Run conclusion and state serial |
| Scheduled read-only plan | Undetected drift between changes | Exit code and the owner notification |
Figure 4 shows the gates in order, and Figure 5 contrasts a static-key pipeline with the recorded path.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Merge to a commit SHA with the lock file"] --> B["Plan job with the read role"]
B --> C["Save plan file, JSON and SHA-256"]
C --> D{"Approval for that hash?"}
D -->|"no"| D1["Stop before apply credentials"]
D -->|"yes"| E["Apply job behind the environment gate"]
E --> F["Queue keyed on the OSS prefix"]
F --> G{"Tablestore lock acquired?"}
G -->|"no"| G1["Wait or fail, never force-unlock"]
G -->|"yes"| H["Apply the downloaded plan"]
H --> I{"Apply finished?"}
I -->|"no"| I1["Partial state: fresh plan, then import or retry"]
I -->|"yes"| J["Verify with a no-change plan"]
J --> K["Publish account, region, identity and hash"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,C,H,K primary;
class B,E,F secondary;
class G,J ok;
class D1,G1,I1 danger;
class D,I warn;
The change record is not the workflow log. A workflow log answers what happened in one run; the change record answers what exists now and how to rebuild it. Publish the second one, and keep the first only as long as the retention policy allows.
Recover API Failures and Audit Billable Leftovers
A partial apply is a normal failure, not a corrupted state. Terraform stops at the first error, records the resources completed before it, and leaves the failing one either absent or present and tainted. The exit code is non-zero, and the saved plan can no longer be resumed.
Never re-apply the approved file after a failure. It describes a graph that no longer matches reality. Run a fresh plan, read what it proposes for the addresses that did land, and treat any create against an object that exists as an import candidate instead of a retry.
Diagnose the layer before touching state. An expired session, a missing permission, an unactivated product, an exhausted quota, a zone without capacity, a throttle and a name collision all stop the same graph and need different responses. The error reason names the layer; the plan summary does not.
The confusing denial is usually propagation. A RAM policy write returns before every service honours it, and the delay is usually seconds to minutes. Retry with backoff, test the permission directly, and do not recreate a binding that is already correct.
Aliyun reads can lag the write. A RAM attachment can take a moment to appear in every authorization path, and a bucket created in one region is not visible through another region's endpoint. Read the object back with its describe call, order the dependency explicitly, and retry the failing request instead of adding a sleep to the configuration.
Give the retry a budget and a reason. Two retries with backoff cover propagation and throttling; a third failure means the layer is wrong and another attempt only adds noise. Record the error reason, the layer you assigned and the next owner, then stop.
Reconcile in three passes. List state to see which addresses are recorded, run a refresh-only plan to learn what the APIs hold, then decide per address: keep and import, drop without destroying, or replace deliberately. A tainted object is a replace decision, not an import.
Use a removed block when an object should leave state. Declaring it removed with destroy disabled drops the record without calling the API, which is the correct move for an object another team has taken over. Deleting the resource block instead proposes a destroy, and that is a different change.
Targeting is for unblocking, not for finishing. A targeted apply repairs one address and leaves the graph's other promises unverified, so a later full plan surprises the next reviewer. Use targeting to unblock a named dependency, then finish with an untargeted plan.
Force-unlock is a last resort with evidence. Confirm that no run still holds the lock, record the lock ID and the state serial, and only then unlock. The OSS backend stores the lock in Tablestore, so a stuck lock is a database record to inspect rather than a file to delete.
State surgery is the last resort, and it needs a witness. Every removal, import and unlock changes the record of what exists; do it with a second operator reading the same plan, and keep the before and after state serials. The point is not ceremony, it is that a wrong removal is invisible until the next destroy.
Audit billable leftovers by address and by tag. A failed apply can leave an EIP, a disk, a snapshot, a NAT gateway or an SLB instance behind, and each one can appear on the next bill. Search Resource Center by the ownership tag, compare the result with state, and assign every unmanaged object to a person before deleting anything. A KMS key delete is scheduled rather than immediate, so the key stays in a pending state for the window you set.
Turn on cost allocation tags before the spend. A tag added after the invoice is archaeology; a tag activated before the spend turns the bill into an ownership report. The tag key and its allowed values belong in the register, not in a wiki page nobody reads.
Close with evidence, not relief. Confirm the final plan is empty, the identifiers you meant to keep are unchanged, the shared trail and policy still hold the other teams' principals, and temporary roles, locks and artifacts are gone. Attach the plan hash and the verification output to the change record.
Table 7 sorts the common failures by the layer that has to answer them.
| Symptom | Layer | First read | Safe next action |
|---|---|---|---|
| Session expires mid-apply | Credential | Token expiry and role session | Re-assume from the token file, then replan |
| Denial just after a policy write | RAM propagation | Policy read plus a direct permission test | Wait and retry, keep the binding |
| Product API unavailable | Activation | Product status in the console | Activate through the platform owner |
| Quota exhausted on one family | Quota | Quota Center for that region | Request an increase or change family |
| No stock in the selected zone | Capacity | Zone and instance type data | Choose another zone deliberately |
| Name already exists | Global namespace | The existing object and its declarer | Import it or rename, never retry blindly |
| Lock held after a failed run | State backend | Lock ID and last writer | Confirm, then unlock with evidence |
Absent, tainted and recorded are three different states. A recorded object is done; an absent object that exists remotely is an import; a tainted object exists but its last operation failed, so it is a replace decision. Write the classification down before editing, because the same address can move between categories after one refresh.
Recover API Failures and Audit Billable Leftovers
Status: design-only. No Alibaba Cloud account, credential or billable resource was used for this article, and none of the steps below was executed. Every identifier is a placeholder: substitute your own sandbox account, region, VPC and bucket.
Prerequisites. Terraform CLI 1.17.1, aliyun/alicloud 2.2.0, one sandbox account in one region, an OSS state bucket with versioning and a Tablestore lock table, a read-only planner role and a writer role, and one console-created VPC with two vSwitches and a security group. Cost is a few cents for the session; the VPC and vSwitches are free, and the state bucket and lock table are the only persistent objects.
Setup. One root with a provider alias per role, a backend prefix for the workload, and a register that lists the placeholder IDs you copied from the console. The console-created objects have no state address, and the writer role can create a duplicate VPC if you skip the import.
- Run
terraform versionandterraform providersand record 1.17.1 and 2.2.0 rather than the latest resolution. - Confirm the backend prefix, bucket versioning and the lock table before the first plan.
- Fill the register: one VPC, two vSwitches, one security group, the declarer and the evidence.
- Write the resource blocks at their final addresses and add an import block for each object with the canonical ID.
- Plan, read the generated configuration line by line, and remove any literal secret before applying.
- Apply the import plan, remove the import blocks, and plan again. Classify every remaining diff as default, normalisation or real.
- Add a deliberate failure: a duplicate bucket name or a quota-exceeding instance count. Apply and record the exit code and the addresses that landed.
- List state and plan fresh. Import the object that exists, remove the duplicate declaration, and apply the fresh plan.
- Tag every imported object, search Resource Center by that tag, and compare the result with state.
- Destroy the workload through the root, confirm the final plan is empty, and check for EIPs, disks and snapshots that outlived it.
| Address after step 7 | State | API reality | Correct action |
|---|---|---|---|
| VPC and first vSwitch | Recorded | Exist and unchanged | Leave them alone |
| Second vSwitch | Recorded or absent | May exist with a default name | Import at the planned address |
| Duplicate bucket name | Absent | Exists under another owner | Rename, never retry the create |
| Security group | Recorded | Exists with console rules | Encode the rules or import them |
| Resource tag | Only if declared | Set on some objects | Reconcile by tag search, not by memory |
Expected observation. Step 6 ends with an empty plan or a short list of named exceptions, not a replacement. Step 7 exits non-zero after the earlier addresses are recorded, and the fresh plan in step 8 proposes an import or a single create rather than repeating the whole set.
Failure check. If step 6 wants to create the VPC, the import landed at a different address or in a different region. If step 8 proposes to destroy the security group, the imported address is not the one the configuration uses. If the tag search finds objects that state does not, the failed apply created a companion outside the graph and that object needs an owner.
Cost and cleanup. Destroy the imported resources through the root, release any EIP or disk the failed apply left behind, cancel any pending KMS deletion you did not intend, confirm the shared trail and policy still hold the other principals, then remove the temporary roles and the test prefix.