Post

The OpenTofu 1.9 `-exclude` Flag That Silently Leaves Residual Resources

The OpenTofu 1.9 `-exclude` Flag That Silently Leaves Residual Resources: hands-on walkthrough with commands, expected outputs and a checklist. Learn how.

The OpenTofu 1.9 `-exclude` Flag That Silently Leaves Residual Resources

Running tofu apply -exclude during an incident feels like a clean, surgical way to avoid touching fragile infrastructure while rolling out an urgent fix. What the plan does not tell you is that OpenTofu removes excluded nodes and their immediate destructive edges from the execution graph before calculating dependency updates. The command finishes with zero errors, yet unmanaged cloud resources remain live, incurring billing costs and quietly leaking traffic.

TL;DR: OpenTofu 1.9.0 introduces native target exclusion via -exclude, but omitting upstream resources severs dependency vertices needed for downstream recreation cycles. When upstream changes force a resource replacement while that upstream is excluded, OpenTofu drops the destroy phase and creates orphaned cloud assets. This guide explains DAG pruning mechanics, highlights silent failure modes, and outlines safe execution boundaries.

What you will walk away with

  • A structural diagnosis of how OpenTofu 1.9.0 prunes dependency nodes during plan compilation.
  • The exact failure pattern where security group exclusions orphan dependent load balancers.
  • A battle-tested verification checklist to validate state graph completeness before applying partial changes.

How Does OpenTofu 1.9 Evaluate the Exclude Flag?

OpenTofu 1.9 evaluates -exclude by filtering matching resource addresses from the Directed Acyclic Graph (DAG) during the graph-construction phase, freezing their attributes as static state data. Any downstream resource that depends on an excluded resource’s exported values computes its plan against the existing state values rather than evaluating upstream diffs or planned lifecycle events.

Target exclusion is a CLI-driven graph filtering operation that drops specified resource addresses from execution traversal while preserving their last known state attributes.

graph TD
    SG["aws_security_group.ingress (EXCLUDED)"]
    ALB["aws_lb.public_alb (TARGETED)"]
    TG["aws_lb_target_group.core (TARGETED)"]

    SG -.->|"Edge Severed"| ALB
    ALB -->|"Active Dependency"| TG

When you pass the -exclude flag, OpenTofu parses the CLI arguments and modifies graph generation inside the terraform/graph.go engine. Excluded nodes are marked as unvisited. If a resource requires recreation due to an attribute update driven by the excluded parent, the engine cannot construct the corresponding NodeAbstractResourceInstanceDestroy vertex.

Operation Mode Upstream Evaluation Downstream Destroy Triggers Graph Edge Integrity Winner / Best For
tofu apply (Full) Complete Guaranteed Complete DAG Normal deployments
tofu apply -target=... Targeted chain only Explicit paths only Truncated DAG Emergency surgical patches
tofu apply -exclude=... Skipped Dropped across severed boundaries Partially severed Non-dependent component bypass

Treat -exclude as an explicit instruction to sever graph dependencies, not as a benign filter for plan readability.


Why Does tofu apply -exclude Leave Orphan Load Balancers?

Excluding a security group module while applying changes to attached load balancers causes OpenTofu to lose visibility into physical recreation requirements. If an ingress rule change alters a port configuration that triggers an AWS Application Load Balancer (ALB) listener recreate, excluding the security group drops the link between the existing network interface and the new resource plan.

Consider this setup at Aicademy where the security group module is excluded during an urgent listener port change:

1
tofu apply -exclude='module.security_groups' -auto-approve

The CLI returns an exit code of 0 and shows one resource created:

1
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

OpenTofu created the new target group and listener binding, but failed to signal the teardown of the old ALB instance. AWS refuses to release the previous elastic network interface (ENI) binding because the excluded security group still holds an active attachment reference to it. The old load balancer becomes an untracked, orphaned asset in your AWS account.

To fix this silent detachment, stop excluding the parent network boundary. Target both edges of the relationship simultaneously, or let the complete graph evaluate state updates:

1
2
3
4
5
6
7
8
- tofu apply -exclude='module.security_groups'
+ # Option 1: Evaluate the full dependency chain explicitly
+ tofu apply \
+   -target='module.security_groups.aws_security_group.lb_ingress' \
+   -target='module.compute.aws_lb.public_alb'
+
+ # Option 2: Apply the full plan if provider authentication is properly scoped
+ tofu apply

If cross-account provider configurations are forcing you to bypass modules due to auth timeouts, avert a cross-account identity crisis with an assume helper function instead of masking structural bugs with CLI flags.

Never execute -exclude across resources that share ingress, egress, or subnetwork association attributes.


How Can You Safely Apply Changes Without Severing References?

You can safely isolate changes by structuring decoupled root modules or validating state diffs with machine-readable plans before executing. When working with complex multi-environment layouts, you can cut 80% of multi-region provider boilerplate with OpenTofu 1.9 by isolating state boundaries cleanly instead of running partial applies on a monolithic state file.

If an operational incident forces you to run a partial apply with -exclude, verify your state graph manually before committing:

  • Run tofu plan -exclude=... -out=safe.plan to generate an execution artifact.
  • Inspect the JSON representation via tofu show -json safe.plan | jq '.resource_changes[] | select(.change.actions[] == "delete")'.
  • Confirm no upstream network constructs (aws_security_group, aws_subnet, aws_vpc) are absent from the plan if downstream compute instances report updates.
  • Run tofu graph and verify no isolated islands exist for resources being modified.

If your build targets are sensitive to host-level platform bugs, verify why your OpenTofu Windows ARM64 builds are probably executing x86 emulation to prevent runtime binary inconsistencies from masking infrastructure graph bugs.

Save the exclusion plan to a file and parse resource actions via JSON before executing an uninspected partial apply.


Bottom Line

Use -exclude exclusively on isolated leaf nodes—like metrics monitors, log alarms, or standalone DNS records—that possess zero downstream consumers in the DAG. When updating networking, storage, or security primitives, always evaluate the complete dependency tree to prevent unmanaged cloud waste. Next in the OpenTofu 1.9 series, we will unpack the internal mechanics of ephemeral resource state lifecycles and secret leakage paths.


FAQ

Does OpenTofu 1.9 warn you if an excluded resource breaks a downstream dependency?

No. OpenTofu treats excluded resources as static data sources and assumes their current state satisfies all downstream constraints. It will not print a warning even if an excluded node’s omitted changes would structurally alter a downstream resource.

What is the difference between -target and -exclude in OpenTofu 1.9?

-target builds a subgraph including the specified node and all of its ancestors required to satisfy dependencies. In contrast, -exclude starts with the complete graph and slices out the specified nodes, breaking ancestor-descendant relationships without warning.

How do you identify orphan resources left behind by an excluded apply?

Run tofu plan without flags against the environment. The resulting output will detect drift and attempt to reconcile or destroy resources that were left unmanaged or incomplete during the partial execution.

Can you pass multiple -exclude patterns to a single OpenTofu command?

Yes. You can declare multiple -exclude flags on the command line (e.g., tofu plan -exclude='module.vpc' -exclude='module.rds'). Each flag subtracts matching resource targets during the graph compile phase.

Part of the series: opentofu-19-series

  1. Cut 80% of Multi-Region Provider Boilerplate With OpenTofu 1.9
  2. The OpenTofu 1.9 `-exclude` Flag That Silently Leaves Residual Resources (you are here)

Further Reading


🚀 Ready to get hands-on? Spin up an interactive AI or Kubernetes Sandbox at Aicademy Labs for free.

This post is licensed under CC BY 4.0 by the author.