Why move
Most OCI teams store Terraform state in Object Storage in one of two ways:
backend "s3"against the S3 Compatibility API. It needs customer secret keys and a set ofskip_*flags, and its locking relied on DynamoDB or, in newer Terraform, S3 conditional writes. Not every S3 feature behaves the same against OCI.backend "http"with a pre-authenticated request (PAR). There's no locking at all, and the PAR URL is a bearer credential that often ends up in Git.
The native oci backend authenticates with normal OCI auth (API key, instance principal, resource principal, security token, OKE workload identity). It locks by writing a lock object with If-None-Match: *. It can encrypt with a Vault key or a customer-supplied key. The HashiCorp docs for it start at Terraform v1.12, so check terraform version on every runner before you switch.
1. Create the state bucket
Use one bucket per trust boundary (for example prod versus non-prod), not one per stack. Separate stacks by key.
NS=$(oci os ns get --query data --raw-output)
COMP=ocid1.compartment.oc1..tfstate
oci os bucket create --compartment-id "$COMP" --name tfstate-prod \
--public-access-type NoPublicAccess --versioning Enabled \
--kms-key-id ocid1.key.oc1..example
Versioning is what saves you after a corrupted or truncated state write. HashiCorp recommends enabling it.
If you use a Vault key on the bucket, or kms_key_id in the backend, Object Storage must be allowed to use it:
Allow service objectstorage-<region-identifier> to use keys in compartment security where target.key.id = '<key-ocid>'
2. IAM for the runners
The backend needs object inspect, read, create and delete on the state bucket only:
Allow group tf-prod-runners to read buckets in compartment tfstate where target.bucket.name = 'tfstate-prod'
Allow group tf-prod-runners to manage objects in compartment tfstate where target.bucket.name = 'tfstate-prod'
For pipeline agents on OCI compute, use a dynamic group and auth = "InstancePrincipal" instead of API keys. On OKE runners, use OKEWorkloadIdentity. For least privilege, the backend documents the operations it calls: GetObject, PutObject, DeleteObject, HeadObject and the multipart upload calls. You can express these with request.permission conditions if your policy standard requires it.
Tip
Give read-only consumers, such as a
terraform_remote_statelookup from another stack, a policy that allows onlyOBJECT_INSPECTandOBJECT_READ. Then a downstream stack can't overwrite upstream state by mistake.
3. Configure the backend
Keep the backend block minimal and pass environment-specific values with partial configuration:
terraform {
required_version = ">= 1.12.0"
backend "oci" {}
}
backend-prod.hcl:
bucket = "tfstate-prod"
namespace = "mytenancynamespace"
region = "eu-frankfurt-1"
key = "network/hub/terraform.tfstate"
workspace_key_prefix = "tf-state-env"
auth = "InstancePrincipal"
kms_key_id = "ocid1.key.oc1..example"
terraform init -backend-config=backend-prod.hcl
| Argument | Required | Notes |
|---|---|---|
bucket, namespace | Yes | Can't be set from environment variables |
key | No | Defaults to terraform.tfstate; set it per stack |
region | Effectively | The bucket's region |
auth | No | APIKey, InstancePrincipal, ResourcePrincipal, InstancePrincipalWithCerts, SecurityToken, OKEWorkloadIdentity |
config_file_profile | No | Profile in ~/.oci/config for API key or security token auth |
workspace_key_prefix | No | Defaults to tf-state-env |
kms_key_id | No | Vault master key for the state object |
sse_customer_key, sse_customer_key_sha256, sse_customer_algorithm | No | SSE-C; algorithm AES256 |
Non-default workspaces store state at <workspace_key_prefix>/<workspace>/<key>.
4. Migrate existing state
Run the migration from a machine that holds the current lock-free view of state, during a change freeze for that stack.
# 1. Make sure nobody is applying, then take a local copy
terraform state pull > pre-migration-$(date +%F).tfstate
# 2. Replace backend "s3" {...} or backend "http" {...} with backend "oci" {}
# 3. Re-initialise with migration
terraform init -migrate-state -backend-config=backend-prod.hcl
# 4. Prove nothing changed
terraform plan -detailed-exitcode # exit 0 = no changes
Terraform asks whether to copy the existing state into the new backend. Answer yes. After a clean plan, revoke what the old method needed:
# Old S3 approach: delete the customer secret key used by the pipeline
oci iam customer-secret-key delete --user-id "$USER" --customer-secret-key-id "$KEY_ID"
# Old HTTP approach: delete the PAR
oci os preauth-request delete --namespace "$NS" --bucket-name tfstate-prod --par-id "$PAR_ID"
Warning
If you keep both backends' objects in the same bucket under different names, a stale pipeline still configured for the old backend will apply against the old state copy and quietly fork your infrastructure. Rename or delete the old state object once migration is verified.
5. Locking behaviour and stale locks
On plan, apply and destroy, the backend creates a lock object next to the state, for example network/hub/terraform.tfstate.lock. A second run fails with a lock error until the first finishes.
When a runner dies mid-apply, the lock stays behind:
terraform force-unlock <LOCK_ID> # ID is printed in the lock error
# Last resort, if force-unlock can't run:
oci os object delete --namespace "$NS" --bucket-name tfstate-prod \
--object-name network/hub/terraform.tfstate.lock --force
Caution
Only remove a lock after confirming that the process holding it is dead (check the pipeline run and the runner host). Two concurrent applies on the same state can create duplicate resources and leave state that matches neither.
6. Recover a bad state write
Versioning lets you roll back:
oci os object list-object-versions --namespace "$NS" --bucket-name tfstate-prod \
--prefix network/hub/terraform.tfstate \
--query 'data[].{v:"version-id",m:"time-modified",size:size}' --output table
oci os object get --namespace "$NS" --bucket-name tfstate-prod \
--name network/hub/terraform.tfstate --version-id <version-id> --file good.tfstate
terraform state push good.tfstate # refuses if serial/lineage conflict; read why before using -force
terraform plan
Design notes for large estates
| Decision | Recommendation |
|---|---|
| State granularity | One state per blast radius (hub network, each spoke, each app). Large states make plans slow and increase API throttling |
| Cross-stack reads | terraform_remote_state with read-only IAM, or publish outputs to OCI Vault secrets or tags |
| Runners | Instance principal or workload identity. No long-lived API keys in CI |
| Encryption | Bucket-level Vault key is enough for most. SSE-C means you own key distribution to every runner |
| Retention | Lifecycle rule to delete previous object versions older than your recovery window |
Prevent it next time
- Pin
required_versionso an old Terraform binary can't initialise a stack it can't lock. - Alarm or audit on
DeleteObjectagainst the state bucket, outside the lock object pattern. - Keep
-detailed-exitcodeplans in CI so drift and broken state show up before an apply. - Document the
force-unlockprocedure, and who may run it, in the on-call runbook.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get