Home / OCI

OCITroubleshootingAdvanced

Terraform on OCI never reaches a clean plan: tag defaults, autoscalers and forced replacements

Every OCI plan shows changes nobody made, or wants to replace an instance. Classify the diff, fix its owner, and make drift checks useful again without hiding real changes.

Deepak Bhardwaj7 min read

Applies toTerraform CLI with the oracle/oci provider, OCI Resource Manager, OCI tag defaults, instance pools and OKE node pools

Symptoms

  • terraform apply succeeds, and the next terraform plan still shows changes.
  • Oracle-Tags.CreatedBy and Oracle-Tags.CreatedOn are removed on apply.
  • A plan shrinks a node pool that the autoscaler has just grown.
  • A plan wants to destroy and recreate an instance because a new platform image was published.
  • Nobody reads the plan output anymore because it is always noisy.

The last one is the real risk. A genuine security rule change is invisible among 200 tag updates.

Check 1: reduce the plan to changed attributes

Save the plan and process the JSON. Reading the rendered text does not scale past a few resources.

terraform plan -out=tf.plan
terraform show -json tf.plan > plan.json

# Count by action
jq -r '.resource_changes[].change.actions | join("+")' plan.json | sort | uniq -c

# One line per changed top-level attribute
jq -r '
  .resource_changes[]
  | select(.change.actions != ["no-op"] and .change.actions != ["read"])
  | .address as $a | .change as $c
  | (($c.after // {}) | keys[]) as $k
  | select($c.before[$k] != $c.after[$k])
  | [$a, ($c.actions | join("+")), $k] | @tsv' plan.json

Now look at what forces replacements:

jq -r '.resource_changes[]
  | select(.change.replace_paths != null)
  | [.address, (.change.replace_paths | tostring)] | @tsv' plan.json

Caution

delete+create or create+delete on an instance, volume, database or load balancer means an outage and possibly data loss. Do not apply a plan to "clear the noise" until every replacement is explained.

Check 2: separate drift from configuration differences

A diff has three possible origins, and each has a different fix.

terraform plan -refresh-only
Result Meaning Where to fix it
Refresh-only shows a change Something altered the resource outside Terraform Find the other writer
Refresh-only is clean, normal plan shows a change Configuration differs from state HCL, variables or data sources
Same diff returns immediately after apply API normalises, rejects or re-adds the value Provider setting or the value itself

For the first case, use OCI Audit to name the writer before you change any code. If the writer is an autoscaler or a tag default, change who owns the attribute. If it is a person, restore the value.

Fix 1: tag defaults and automatic tags

Tag defaults add keys at create time. Terraform sees keys that the configuration does not contain and plans to remove them. For tags that are owned outside Terraform, set the provider argument:

provider "oci" {
  region = var.region

  ignore_defined_tags = [
    "Oracle-Tags.CreatedBy",
    "Oracle-Tags.CreatedOn",
  ]
}

Details that matter:

  • Entries are namespace.key. The list has a documented maximum size of 100.
  • It is set on the provider only and applies to all resources managed through that provider configuration.
  • Repeat it in every aliased provider "oci" block. Multi-region stacks often fix only the default one.

Do not add tags that Terraform should own, such as a cost centre. Ignoring them means a wrong value is never reported.

If only a few resources are affected, use a narrower exception:

lifecycle {
  ignore_changes = [defined_tags["Operations.PatchGroup"]]
}

Tags copied to secondary resources

OCI can propagate tags from a primary resource to a secondary one, for example from an instance to its VNIC. If the configuration manages both, declare the same tags on both:

locals {
  common_defined_tags = {
    "Operations.Environment" = var.environment
    "Operations.CostCenter"  = var.cost_center
  }
}

resource "oci_core_instance" "app" {
  # compartment_id, shape, source_details and other required arguments omitted
  defined_tags = local.common_defined_tags

  create_vnic_details {
    subnet_id    = var.subnet_id
    defined_tags = local.common_defined_tags
  }
}

Match the case of namespaces and keys to the definitions in IAM. Treat a diff that differs only by case as a configuration bug.

Fix 2: give autoscaled sizes one owner

A pool size has two writers when an autoscaler is active. Terraform should set the initial value only:

resource "oci_core_instance_pool" "web" {
  compartment_id            = var.compartment_id
  instance_configuration_id = oci_core_instance_configuration.web.id
  size                      = 3

  placement_configurations {
    availability_domain = var.availability_domain
    primary_subnet_id   = var.subnet_id
  }

  lifecycle {
    ignore_changes = [size]
  }
}

For an OKE node pool managed by the Cluster Autoscaler, the nested path is:

lifecycle {
  ignore_changes = [node_config_details[0].size]
}

Warning

After this, editing size in HCL does nothing. Put minimum and maximum in the autoscaling configuration and review those values instead.

The same rule applies to load balancer backends registered by a controller or instance pool. Do not also declare them as oci_load_balancer_backend resources.

Fix 3: stop image data sources from replacing instances

This pattern changes its result when Oracle publishes an image:

data "oci_core_images" "ol" {
  compartment_id           = var.compartment_id
  operating_system         = "Oracle Linux"
  operating_system_version = "9"
  shape                    = var.shape
  sort_by                  = "TIMECREATED"
  sort_order               = "DESC"
}

If images[0].id feeds source_details.source_id, every new image can produce a boot volume or instance replacement, depending on the provider version and arguments.

Pin the image OCID in a reviewed variable file for stateful servers:

variable "image_ocid" {
  type = string
  validation {
    condition     = startswith(var.image_ocid, "ocid1.image.")
    error_message = "image_ocid must be an image OCID."
  }
}

For instance pools, let the instance configuration change and control the rollout separately. Use create_before_destroy on the instance configuration, because a pool still references the old one.

Also check instance metadata. Rendered user_data that includes a timestamp, a secret or an unordered map can change on every run. Remove the unstable input rather than ignoring all metadata.

Fix 4: values that can't be cleared

Oracle documents that many optional arguments can't be unset by deleting them or passing an empty string. The plan may look clean while the old value remains in OCI. Check the resource directly:

oci compute instance get --instance-id "$INSTANCE_OCID" \
  --query 'data.{name:"display-name",defined:"defined-tags",freeform:"freeform-tags"}'

Set an explicit new value where the API has one, for example false, instead of removing the line. If the API can't clear the property, change the resource deliberately.

Protect critical resources while you clean up

lifecycle {
  prevent_destroy = true
}

Add a pipeline gate too, because prevent_destroy disappears when the whole resource block is deleted:

jq -e '
  [.resource_changes[]
   | select(.change.actions | index("delete"))
   | select(.type | test("^oci_(core_instance|core_volume|database_|load_balancer_load_balancer)"))
  ] | length == 0' plan.json

jq -e exits non-zero when the expression is false, so the job fails and needs an explicit approval.

Verify

Run two consecutive plans with no code change:

terraform plan -detailed-exitcode -lock-timeout=5m

Exit code 0 is clean, 1 is an error and 2 means changes are present. Then make one harmless out-of-band change in a test compartment and confirm that the plan reports it. A clean plan caused by overly broad ignore_changes is not a fix.

Prevent it next time

  • Review each ignore_changes entry. Require a comment that names the other owner, and reject ignore_changes = all.
  • Commit .terraform.lock.hcl and upgrade the provider in its own change. Capture a plan before and after.
  • Coordinate new tag defaults with stack owners. A tenancy-wide default affects every stack at once.
  • Schedule -detailed-exitcode plans and alert on 2.
  • Keep one configuration as the owner of each resource. Two stacks managing the same resource will never converge.