<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by StackGuardian on Medium]]></title>
        <description><![CDATA[Stories by StackGuardian on Medium]]></description>
        <link>https://medium.com/@StackGuardian?source=rss-0cb33cc953f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2SIz1hr1clHoQVZSkPLjYw.png</url>
            <title>Stories by StackGuardian on Medium</title>
            <link>https://medium.com/@StackGuardian?source=rss-0cb33cc953f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:46:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@StackGuardian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Infrastructure Drift Explained: Causes, Risks, and Fixes | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/infrastructure-drift-explained-causes-risks-and-fixes-blog-stackguardian-c3f5b403d372?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3f5b403d372</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 13:16:01 GMT</pubDate>
            <atom:updated>2026-11-26T13:16:01.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3ooJf3iXSgvRq-jYA5Kqg.png" /></figure><ul><li>Infrastructure drift is the gap between what your last applied IaC configuration declares and what is running in your cloud account. Manual console edits, incident hotfixes, and cloud provider updates are the usual sources.</li><li>Drift causes deployment failures, security vulnerabilities, and operational inconsistencies. An unnoticed change can also make the next apply destroy or recreate a resource you never meant to touch.</li><li>Terraform and OpenTofu detect drift during every plan, and -refresh-only lets you review external changes without proposing any infrastructure change. HCP Terraform health assessments add scheduled checks. AWS CloudFormation drift detection adds stack-level checks that run on demand or through an AWS Config rule. Each has documented limits.</li><li>Every drift finding ends in one of three decisions: revert the change, accept it into state, or update the configuration to match it.</li><li>StackGuardian covers the loop with four pieces: an Automated Drift Check setting, an “On Drift Detection” webhook event, a “SG Drifted” status in Cloud Inventory and Policy Sets that can fail a plan which would delete a resource.</li></ul><p>An engineer opens a port in the AWS console at 2 a.m. to stop an outage. The incident closes, the port stays open, and the Terraform code that is supposed to describe that security group says nothing about it. Nobody notices for weeks. Infrastructure as Code promises that the repository is the source of truth. Drift is what happens when the running infrastructure stops matching it. The mismatch shows up later as a failed deployment, a surprise line in a plan or an audit finding.</p><p>This guide explains what infrastructure drift is, why it happens and what it puts at risk. It then covers detection in Terraform, OpenTofu, HCP Terraform and AWS CloudFormation. Next, it covers three ways to resolve a finding and the controls that stop drift from accumulating. One running example follows a payments team whose security group changed outside code. The last sections show how StackGuardian handles the same loop. Companion guides on policy as code and <a href="https://www.stackguardian.io/post/brownfield-infrastructure">brownfield infrastructure</a> cover adjacent topics in depth, so this piece links to them instead of repeating them.</p><h3>What Is Infrastructure Drift in Plain Language</h3><p>Infrastructure drift is any difference between the infrastructure your last applied code describes and the infrastructure that exists. HashiCorp’s Well-Architected Framework puts it plainly: infrastructure drift occurs when your actual infrastructure state differs from your Terraform configuration, often due to manual changes, cloud provider updates, or unauthorized modifications. The same page lists the consequences as deployment failures, security vulnerabilities, and operational inconsistencies.</p><p>Three things are in play whenever drift is discussed. The configuration is the code in your repository. The state is the record the IaC tool keeps of what it created. The real infrastructure is what exists in the cloud account right now. A healthy setup keeps all three aligned, and drift breaks that alignment.</p><p>Two kinds of breaks are worth separating. Configuration drift happens when an external change invalidates what your code says, such as a teammate changing a security group rule in the console so that it conflicts with the code. State drift happens when an external change to a remote object does not invalidate the configuration. The distinction affects tool choice because some tools only detect one kind, a point the HCP Terraform section below returns to.</p><p>Drift is also not the same as intentional change. A deliberate update that goes through a pull request and a pipeline is a change. A modification that bypasses the pipeline is drift, even when it was the right call. Code that is merged but not yet applied is a pending change and not drift, although a plain plan shows both.</p><p>The running example in this guide is a payments team that manages an AWS security group for its API with Terraform. During an incident, an engineer adds an ingress rule for port 8080 from 0.0.0.0/0 in the console. That single edit is the drift the rest of the guide detects, assesses, and resolves. Understanding the definition is the easy part. The harder question is why drift keeps appearing in teams that already use IaC, which the next section answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntfOp3ntl5yPvWL28dGOTw.png" /></figure><h3>Common Causes of Infrastructure Drift in Cloud Environments</h3><p>Drift comes from a small set of repeating behaviors. Most of them are reasonable decisions made under pressure, which is why discipline alone rarely prevents them. Manual console and CLI edits are a common cause. Someone needs a change faster than a pull request allows, so they make it directly. The security group edit in the running example belongs here. Incident hotfixes are the second source, and the most sympathetic one. During an outage, the fastest route to recovery is usually the console. The fix works, the incident closes, and the follow-up ticket to codify the change slips down the backlog.</p><p>Cloud provider updates introduce drift without any human involvement. A provider can change a default, add an attribute or modify a managed resource. The next plan then shows a difference nobody caused. Other automation touching the same resources is a quieter cause. An autoscaler, a security scanner with auto-remediation, or a second Terraform workspace that manages overlapping resources can all change attributes your configuration also controls. Partial or failed applies round out the list. If an apply stops halfway, some resources match the new configuration and others do not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwWtJ0f_kFfJegNfTxxdXw.png" /></figure><p>With the causes mapped, the next question is what drift costs when nobody catches it.</p><h3>Risks of Unmanaged Infrastructure Drift for Security and Reliability</h3><p>The cost of drift depends on what changed and how long it stayed hidden. Four risks recur.</p><p>Security exposure comes first. In the running example, the console edit opened port 8080 to the entire internet. Because the change never passed through code review or policy checks, no reviewer saw it and no scanner tied to the pipeline evaluated it. The exposure lives until someone happens to look.</p><p>Unintended destroy and recreate comes second. HashiCorp’s resource drift tutorial warns that when real infrastructure no longer matches state and configuration, Terraform will attempt to reconcile it, which may unintentionally destroy or recreate resources. A drifted attribute that forces replacement can turn a routine apply into an outage. Compliance gaps come third. Auditors compare what a control says should exist with what exists. A resource that diverged from its declared configuration shows the control did not hold, even if nothing bad happened. Operational inconsistency is the fourth. When staging and production were built from the same code but have since diverged, a bug that reproduces in one environment disappears in the other, and incident response slows down. Knowing the risks makes detection the obvious priority. The next two sections cover how each major tool finds drift, starting with Terraform and OpenTofu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGD_uTOsRF2xyKUmyvs2kg.png" /></figure><h3>How to Detect Infrastructure Drift With Terraform and OpenTofu</h3><p>Terraform detects drift as part of ordinary planning. Before it compares configuration to state, a plan refreshes state from the real infrastructure. When the refresh finds differences, the plan opens with a note. The same tutorial shows the wording: “Terraform detected the following changes made outside of Terraform since the last “terraform apply”:”.</p><p>For the running example, a team reproducing the console edit would see the drift like this. The commands below create the drift with the AWS CLI, then check for it with a refresh-only plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gl_CmHwef-g49eRGcu8G3Q.png" /></figure><p>The -refresh-only mode is the cleanest way to ask the question &quot;what changed outside Terraform?&quot; According to the Terraform plan documentation, it creates a plan whose goal is only to update the state and any root module output values to match changes made to remote objects outside of Terraform. A normal plan can mix drift and intended changes in one output, so the refresh-only plan keeps the two separate. The same documentation says this mode can help when you have intentionally changed remote objects outside the usual workflow, for example while responding to an incident.</p><p>One option works against detection. Setting -refresh=false disables the synchronization step, and the same documentation warns that it causes Terraform to ignore external changes, which could result in an incomplete or incorrect plan. It also cannot be combined with refresh-only mode. Pipelines that use -refresh=false to save API calls are trading drift visibility for speed.</p><p>OpenTofu behaves the same way. The <a href="https://opentofu.org/docs/cli/commands/plan/">OpenTofu plan documentation</a> describes -refresh-only as creating a plan whose goal is only to update OpenTofu state and root module output values to match changes made outside OpenTofu. Applying works too: <a href="https://opentofu.org/docs/cli/commands/apply/">tofu apply</a> supports the planning modes of tofu plan when no saved plan file is passed. A manual plan finds drift only when someone runs it. Teams that want recurring coverage need scheduled detection, which HCP Terraform provides directly and CloudFormation provides through an AWS Config rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37r5nsavV7FxY9jv8eIp9Q.png" /></figure><h3>Drift Detection in HCP Terraform and AWS CloudFormation</h3><p>Scheduled drift detection removes the need to remember to run a plan. HCP Terraform offers it through health assessments, and CloudFormation offers it through an AWS Config rule. Both have limits to know before relying on them.</p><h3>How HCP Terraform Health Assessments Detect Drift</h3><p>HCP Terraform runs drift detection as part of health assessments, which also include continuous validation of the custom conditions in your configuration. The health assessments documentation sets several requirements. Health assessments are available in the Standard and Premium editions. Workspaces must use remote or agent execution mode. Drift detection needs Terraform 0.15.4 or later, and running drift detection with continuous validation needs 1.3.0 or later.</p><p>The same page documents limits. HCP Terraform does not modify infrastructure as part of an assessment, so it reports and never repairs. Drift detection covers configuration drift only: the documentation states that it does not detect state drift. Assessments pause if the latest run ended in an errored state, which leaves a gap in coverage after a failed apply. Because an assessment creates a speculative plan, a data source whose value changed since the last run can cause a check to fail before the infrastructure itself changed, producing a false positive. The documentation’s cadence example uses a 24-hour schedule.</p><h3>How AWS CloudFormation Drift Detection Checks Stacks</h3><p>CloudFormation approaches the problem at the stack level. Its <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html">drift detection documentation</a> defines drift as a difference between a stack’s actual configuration and its expected template configuration, including when a property or resource has been deleted. Stacks report DRIFTED, IN_SYNC, or NOT_CHECKED. Resources report MODIFIED, DELETED, IN_SYNC or NOT_CHECKED. Property differences are labeled ADD, REMOVE or NOT_EQUAL.</p><p>The limits are explicit. CloudFormation determines drift only for property values explicitly set in the template or through template parameters, excluding default values. It does not run drift detection on the KMSKeyId property of any resource. Nested stacks are not covered when you check the parent stack, so each nested stack needs its own drift detection operation. The page describes detection and leaves corrective action to you. Periodic checks come from the AWS <a href="https://docs.aws.amazon.com/config/latest/developerguide/cloudformation-stack-drift-detection-check.html">Config managed rule</a> cloudformation-stack-drift-detection-check, which runs the DetectStackDrift operation on each stack. The rule has a maximum execution time of 15 minutes, so it may time out before it evaluates every stack in a large account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmnRkmuk3FWKy1jvZDAOag.png" /></figure><p>Detection answers “what changed”. It does not answer “what should we do about it”, which is the decision the next section structures.</p><h3>Three Ways to Fix Infrastructure Drift Once Detected</h3><p>Every drift finding resolves in one of three ways. The HashiCorp tutorial on resource drift walks through all three, and HashiCorp’s Well-Architected guidance describes the same choice as running a new apply to restore the desired state, or updating the configuration to match the new state.</p><p><strong>Revert the change.</strong> Run a normal terraform apply without -refresh-only. Terraform attempts to undo the manual change and return the resource to what the code says. In the running example, this closes port 8080. Reverting is right when the change was a mistake or an unauthorized modification.</p><p><strong>Accept the change into state.</strong> Run a refresh-only apply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ouu_QeNPgvZh2KOgxW5zQ.png" /></figure><p>At the prompt, Terraform writes the changes to state without modifying real infrastructure. The tutorial warns that there is no undo and that only yes is accepted to confirm. Accepting only updates state. The configuration still differs from reality, so the next plan will continue to propose reverting the change unless the code is also updated.</p><p><strong>Update the configuration to match.</strong> Add the change to the code so that configuration, state, and reality agree. If the resource is not yet managed by Terraform, import it first. Terraform&#39;s import documentation describes an import block that specifies the unique infrastructure resource ID to import and declares an address for the imported resource in state. The same page notes that you can write only the import block and run terraform plan with the generate-config-out flag to generate the resource blocks. HashiCorp labels configuration generation as experimental in Terraform 1.5, and the target file must not already exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRRduQ12A8cdCzJ4IxpXGQ.png" /></figure><p>The import ID for this rule resource is the security group rule ID, which starts with sgr-. Choosing between the three depends on the change itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_ba-cI0Wp7-NyHn7N9RWQ.png" /></figure><p>For the payments team, port 8080 open to the whole internet is a revert. The incident is over, the exposure is the risk, and nothing in the change deserves a place in code. A team that instead needed 8080 reachable from one internal CIDR would update the configuration with that narrower rule. Resolving findings one at a time is reactive. The stronger move is to stop most drift from forming, which is the topic of prevention.</p><h3>How to Prevent Infrastructure Drift Before It Starts</h3><p>Prevention works in layers, because no single control covers every cause listed earlier.</p><ul><li>Restrict console write access in production accounts. If engineers cannot create or modify resources by hand, a common cause of drift becomes a permission error that sends them back to the pipeline. Keep a documented break-glass role for incidents, and require that anything done through it is codified afterward.</li><li>Enforce policy as code. Guardrails that evaluate every plan catch dangerous changes whether or not the author remembers the rule. Guardrails also work on plans that follow drift, where destructive replacements tend to appear. The companion guide on policy as code from zero to enforced guardrails covers how to build that layer.</li><li>Route changes through a GitOps workflow. When every change is a reviewed pull request and the pipeline is the only path to production, the repository stays authoritative by design. HashiCorp’s guidance adds a related practice: implement drift detection in the CI/CD pipeline to catch configuration issues before they reach production.</li><li>Schedule detection and alert on it. Detection nobody sees is as weak as no detection. Alerts should be tiered by severity, so that a security or availability finding pages someone while a cosmetic difference waits for a scheduled review.</li><li>Codify what already exists. Resources created before IaC adoption can never be in sync with code that does not exist. The brownfield infrastructure guide covers how to bring them under management.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlWF52B7ZuDUF__oi1IhyA.png" /></figure><p>Those controls are the practices. A platform helps put them into one working loop, and the next section shows how StackGuardian approaches it.</p><h3>How StackGuardian Handles Drift Detection and Remediation</h3><p>StackGuardian covers four parts of the drift loop: scheduled detection, alerting, destructive plans and resources nobody codified.</p><h4>Automated Drift Check on Terraform Workflows</h4><p>StackGuardian’s Terraform Configuration settings include an Automated Drift Check option. According to the <a href="https://docs.stackguardian.io/docs/deploy/workflows/workflows_types/terraform/terraform_configuration/">Terraform Configuration documentation</a>, enabling it allows StackGuardian to run drift checks regularly on your deployed infrastructure. When drift is detected, users can rerun the Workflow to reconcile it, or modify the Terraform configuration to import the changes. Those two options map to the revert and update-configuration paths described earlier. This setting closes the gap that terraform plan leaves open, where detection happens only when someone runs a command.</p><p>StackGuardian also keeps drift checks from competing with deployments. Since v1.31.8, drift runs have <a href="https://docs.stackguardian.io/docs/changelog/1.31.8/">lower priority</a> than user-initiated Workflow runs, so background drift checks yield to deployments.</p><h4>Alerting through the On Drift Detection webhook</h4><p>StackGuardian Workflows can alert on drift through a webhook event named “On Drift Detection”. According to the <a href="https://docs.stackguardian.io/docs/deploy/workflows/workflow_components/webhook/">webhook documentation</a>, the event alerts when configuration drift is detected in the infrastructure. In the Terraform Workflow wizard, webhooks are configured in the Runtime Environment step. Open Advanced Options, then Resources and Events, then Webhook. Each event takes a webhook name, a Generic JSON webhook URL, and an optional secret.</p><p>The webhook documentation shows a sample JSON payload that describes the Workflow’s outcome. It includes the organization, a timestamp, the Workflow Group, the Workflow Run details, the Workflow and a type field. The page does not describe a payload for drift events, so check what a drift event sends before building routing rules on it. A team can still route the webhook into a chat channel or incident tool.</p><h4>Blocking destructive plans with Policy Sets</h4><p>A Tirith policy can fail any plan that would delete a resource, covering the destructive plans drift tends to produce. StackGuardian Policy Sets support two policy engines. Tirith is a JSON-based policy framework, and OPA policies are written in Rego. The Tirith policy below fails any plan that would delete the payments team’s aws_security_group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlltKH9nkZa8mqpRFGYLHQ.png" /></figure><p>The action operation type checks whether a resource is being created, deleted or unchanged. A replacement appears in a plan as a delete plus a create, so the policy also fails plans that replace the resource. The error_tolerance value of 1 tells Tirith to skip the policy when the plan contains no aws_security_group, instead of failing every unrelated plan. Scope is set on the Scope tab, so the payments team can attach the policy to its own Workflow Group. In the Enforcement section of a rule on the Rules tab, setting Action when Policy errors to FAIL blocks the workflow. Attached policies apply to the resulting runs the same way they apply to any other change, which includes the plans that follow drift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lJrWio7PKfNwzoiLizZOg.png" /></figure><h4>Finding resources that never had code</h4><p>Drift detection covers resources that code already describes. Resources created by hand have nothing to drift from. <a href="https://www.stackguardian.io/platform/code">SGCode</a> Cloud Inventory addresses that side. Per the <a href="https://docs.stackguardian.io/docs/sg-code/cloud-inventory/">Cloud Inventory documentation</a>, it displays all resources discovered across connected cloud accounts and assigns each a status. Among them, “Unmanaged” marks a resource not tracked by any IaC state file, and “SG Drifted” marks a StackGuardian-managed resource that has drifted from its expected state. Resources that IaC manages outside StackGuardian appear as Externally Managed. Inventory therefore shows both halves of the problem in one table: what has no code, and what has code it no longer matches.</p><p>The next section ties these pieces into a routine a platform team can follow.</p><h3>A Practical Drift Management Workflow for Platform Teams</h3><ol><li>Detect. Automated Drift Check runs against the payments Workflow and finds that the security group no longer matches its configuration.</li><li>Alert. The “On Drift Detection” webhook posts the finding to the team’s channel. Because the change affects network exposure, the team treats it as a security finding, not a cosmetic one.</li><li>Triage. An engineer reads the plan output and identifies the console edit from the incident. Port 8080 is open to 0.0.0.0/0.</li><li>Decide and fix. The incident is over, and the rule is no longer needed, so the team picks the revert path and reruns the Workflow. If the rule had been legitimate, they would have updated the configuration with a narrower CIDR instead and merged it through a pull request.</li><li>Prevent. The team adds a console write restriction to the production account, keeps a break-glass role for incidents, and attaches a policy that fails any plan that would delete the security group. The follow-up from the incident, codifying any hotfix that should stay, becomes a required step of the incident checklist.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujvHqG7HBaU5MSxsNS9WgQ.png" /></figure><p>A workable routine has five steps, and the payments example runs through all of them.</p><h3>Where Should You Start With Infrastructure Drift Management</h3><p>Infrastructure drift is the predictable result of people and providers changing infrastructure faster than code can follow. It cannot be eliminated, so the goal is to shorten the time between a change and a decision about it. Terraform, OpenTofu, HCP Terraform and CloudFormation each detect drift within their documented limits. None of them decides what to do. Every finding ends in one of three outcomes: revert, accept or update the configuration. The right choice depends on whether the change was a mistake, a harmless provider update, or a fix worth keeping.</p><p>To start, run terraform plan -refresh-only against your most important workspace and read what it reports. Then move detection from manual to scheduled and attach an alert to it. If you manage Terraform through StackGuardian, enable Automated Drift Check in the Terraform Configuration of a Workflow and pair it with the On Drift Detection webhook. For the guardrails that stop drift from turning into an outage, continue with the guide to <a href="https://www.stackguardian.io/post/policy-as-code-from-zero-to-enforced-guardrails-on-your-infrastructure">policy as code</a>.</p><h3>FAQ</h3><h3>1. Is infrastructure drift the same as configuration drift?</h3><p>No. Configuration drift is one kind of infrastructure drift, where an external change invalidates what your configuration says. State drift is the other kind, where an external change does not invalidate the configuration. HCP Terraform drift detection covers only configuration drift, which is why the distinction affects which tool you rely on.</p><h3>2. How often should you run drift detection?</h3><p>There is no universal interval. Run detection often enough that the gap between a change and its discovery stays shorter than your incident or audit cycle. HCP Terraform’s documentation uses a 24-hour schedule as an example. StackGuardian’s documentation describes Automated Drift Check as running regularly. Teams with sensitive resources, such as network rules, usually choose a shorter cycle and alert on findings.</p><h3>3. Does drift detection change my infrastructure?</h3><p>No. Terraform plans, refresh-only plans, HCP Terraform health assessments, and CloudFormation drift detection report differences without changing real infrastructure. A refresh-only apply writes the changes to state, not to the cloud resource. Only a normal apply modifies the infrastructure, and it does so after you approve it.</p><h3>4. Can infrastructure drift be fixed automatically?</h3><p>Detection can run automatically, but the fix still needs a decision. HCP Terraform assessments and CloudFormation drift detection report drift and leave the correction to you. In StackGuardian, when drift is detected, users can rerun the Workflow to reconcile it or modify the configuration to import the changes. Whatever the tool, automatic reverts deserve caution, since a drifted change is sometimes what keeps production up.</p><h3>5. Does OpenTofu support drift detection?</h3><p>Yes. OpenTofu supports -refresh-only on both tofu plan and tofu apply, so you can review and record changes made outside OpenTofu the same way you would in Terraform. Scheduled assessment is a platform feature, so for recurring checks, you need a platform that runs the plans on a schedule.</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/infrastructure-drift"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3f5b403d372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenTofu vs Terraform in 2026: Which Should You Use for IaC? | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/opentofu-vs-terraform-in-2026-which-should-you-use-for-iac-blog-stackguardian-dfb4a7535c36?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb4a7535c36</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[opentofu]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 12:44:51 GMT</pubDate>
            <atom:updated>2026-11-24T12:44:51.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CslSSnAeBmHOGZICXXw5Kw.png" /></figure><ul><li>OpenTofu and Terraform diverged for real in 2026: different licenses, different governance, and a growing list of features that exist in one but not the other.</li><li>OpenTofu carries an OSI-approved MPL 2.0 license under Linux Foundation governance, while Terraform has shipped under HashiCorp’s Business Source License 1.1 since version 1.6.</li><li>OpenTofu has shipped native state encryption, for_each support on provider blocks specifically, early variable evaluation, and the -exclude flag, none of which exist in Terraform’s open-source CLI. Terraform’s main exclusive, Stacks, lives in HCP Terraform rather than the open binary.</li><li>Provider and module compatibility is close to complete on both sides, and independent benchmarking shows performance is nearly identical, since both tools are bottlenecked by cloud API latency, not local processing.</li><li>StackGuardian treats the choice as a non-issue: both tools run as native Workflow types under the same state backend and policy engine, so switching or running both doesn’t require a new platform.</li></ul><p>For nine years, “Terraform” and “the open-source infrastructure as code standard” meant the same thing. That stopped being true in August 2023, when HashiCorp relicensed Terraform under the Business Source License, and a community fork called OpenTofu emerged in response. What started as a defensive move by a handful of vendors has turned into a genuinely separate tool, with its own governance, its own release cadence, and features that never made it into Terraform’s open-source binary.</p><p>By 2026, picking between the two is a real decision, not a formality anyone can skip past with “they’re basically the same.” This post covers what OpenTofu actually is and why it exists; what’s genuinely different between it and Terraform today; licensing, features, compatibility, and performance; the code-level differences worth knowing before you migrate either way; and how StackGuardian runs both natively so the choice doesn’t lock you into one platform.</p><h3>What Is OpenTofu and Why Does It Exist?</h3><p><a href="https://opentofu.org/">OpenTofu</a> is a community-driven, MPL-licensed fork of Terraform, created after HashiCorp relicensed Terraform under the Business Source License in 2023. It’s governed by the Linux Foundation rather than a single vendor, developed by a coalition of companies and independent engineers who wanted the tool to stay under an open license.</p><p>The timeline that produced today’s split:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FC9CmzHfJPefKeekw99Uhw.png" /></figure><p>Both events, the relicense and the IBM acquisition, are why this comparison is worth doing seriously in 2026 rather than treating OpenTofu as a niche alternative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifwXhi-nl7goUuAABCjc_w.png" /></figure><h3>OpenTofu vs Terraform: The 2026 Feature and Governance Comparison</h3><p>The two tools were nearly identical at the moment of the fork. By mid-2026, OpenTofu was at version 1.12.2 with the<a href="https://registry.opentofu.org/"> OpenTofu registry</a> hosting more than 3,900 providers and 23,600 modules, while Terraform sat at 1.14.x. Both are actively developed, but the gap between them has widened every quarter since the fork.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCLAXLz1myMKdgQ6o-W1pg.png" /></figure><p>Independent benchmarking on a mid-size AWS codebase (roughly 400 resources) found performance is not a real differentiator between the two, since both tools spend most of their runtime waiting on cloud provider APIs rather than doing local processing. Don’t pick a side based on speed.</p><h3>What Can OpenTofu Do That Terraform’s CLI Still Can’t?</h3><p>OpenTofu has shipped state encryption, for_each on provider blocks, early variable evaluation including backend configuration, the -exclude flag, loopable import blocks, and OCI registry support for both providers and modules. None of these exist in Terraform’s open-source CLI as of 2026, and the gap has kept widening well past the initial 1.9 release.</p><p><strong>State encryption</strong> is the headline feature. Terraform relies on backend-level encryption, an S3 bucket with server-side encryption enabled, for example, which protects the file at rest in storage but not before it gets there. OpenTofu encrypts state and plan files client-side, before they leave your machine, using pluggable key providers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_YO3X2CxPVoNeXsJQqZzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rpe_FNkzTS98sa8G97LnA.png" /></figure><p>Supported key providers include AWS KMS, GCP KMS, Azure Key Vault, OpenBao, or a PBKDF2 passphrase. If a state file leaks, either from a misconfigured bucket policy or a compromised CI runner, the contents are ciphertext rather than plaintext secrets and access keys.</p><p>Provider for_each, meaning for_each support on provider configuration blocks specifically, lets a single provider block iterate across a map, something Terraform&#39;s for_each meta-argument still doesn&#39;t support on providers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qNBvhnNwqMiX4ghxM9tEg.png" /></figure><p>This removes the repetitive provider block or module duplication that multi-region and multi-account Terraform setups have needed for years.</p><p><strong>The </strong><strong>-exclude flag</strong> is the inverse of -target, letting a plan or apply explicitly skip named resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl57mW8UBAlmQzeQ1p2qkg.png" /></figure><p><strong>Early variable evaluation</strong> lets variables resolve early enough to configure the backend itself, something Terraform’s CLI still doesn’t support, which matters for teams that want dynamic backend configuration without a wrapper script.</p><p>OpenTofu 1.8 also added loopable import blocks, letting a single import block iterate over a for_each map to bulk-import many resources of the same type once their identifiers are known, rather than writing one import block per resource. OpenTofu 1.10 followed with OCI registry support, letting providers and modules be distributed through any OCI-compliant registry rather than only the OpenTofu or Terraform registries. Note that native S3 state locking without DynamoDB isn&#39;t one of the differentiators here; Terraform picked up the same use_lockfile capability on its S3 backend around the same window, reaching GA in Terraform 1.11, so both tools now support it.</p><p>Terraform has two notable exclusives running the other direction. Stacks stays inside HCP Terraform rather than the open binary, alongside Sentinel policies, remote runs, cost estimation, and the private registry, all tied to HashiCorp’s commercial platform. More recently, Terraform 1.14 shipped native resource discovery through a terraform query command and list blocks, letting the CLI ask a provider what resources exist outside state directly. OpenTofu doesn&#39;t have an equivalent yet; a matching tofu query feature request remains open on its repository.</p><h3>How Compatible Are OpenTofu and Terraform in Practice?</h3><p>Migration between the two is close to a non-event for most configurations. The same required_providers block works unchanged in either tool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBMYyunMG5PbKWT5Tp24JQ.png" /></figure><p>Module compatibility sits near 100% as well, with two real exceptions worth knowing before migrating:</p><ul><li>Modules built around Terraform Stacks or Sentinel policy attachments need refactoring, since neither concept exists in OpenTofu</li><li>A handful of providers have published OpenTofu-specific or Terraform-specific releases, though the majority run unchanged on both, and subtle version mismatches can surface in long-tail or internal custom providers built against Terraform’s plugin SDK</li></ul><p>Practically, migration usually means swapping the terraform binary for tofu, with only the terraform_version marker in state changing on the first apply. State stored in S3, GCS, Azure Blob, or any other supported backend works for both tools without modification. The friction that does show up tends to live outside the Terraform configuration itself: CI scripts and Dockerfiles that hardcode the terraform binary name, or module source addresses explicitly pinned to registry.terraform.io, need a manual pass before the swap is complete, since neither one breaks loudly, they just quietly keep resolving against the wrong tool or registry.</p><h3>Does the License Actually Matter for Your Team?</h3><p>The BSL doesn’t affect most end-user teams who simply run terraform apply against their own infrastructure. The license restricts building “a competitive offering,” defined as a product sold to third parties that significantly overlaps HashiCorp’s commercial products. Internal use, including running Terraform inside your own CI/CD pipelines, is explicitly permitted. Each BSL-licensed release also converts to MPL 2.0 automatically, but only four years after that version’s release date, so the restriction isn’t permanent per release, just delayed well past the point where most teams have already moved on to newer versions.</p><p>Where it actually creates friction:</p><ul><li><strong>Vendors building on top of Terraform</strong>: managed CI/CD platforms, drift-detection tools, and policy-as-code systems that wrap or extend Terraform face real legal review under the BSL</li><li><strong>Procurement and compliance review</strong>: the license difference surfaces in legal and vendor review more than in daily engineering work, which matters for regulated industries or enterprises with strict vendor policies</li><li><strong>Cost</strong>: HCP Terraform ended its free tier in March 2026, which reframes the cost conversation for any team relying on it for remote state or execution</li></ul><p>For a platform team running infrastructure internally, the license is mostly a procurement conversation, not an engineering blocker. For anyone building a product on top of IaC, it’s the first question to answer before writing code.</p><p>Worth noting precisely: OpenTofu isn’t a workaround to the BSL; it’s outside the BSL’s scope entirely. It forked from Terraform’s last MPL 2.0 release, published before the relicense took effect, so nothing in OpenTofu’s codebase was ever covered by HashiCorp’s license in the first place. Building a competitive product on OpenTofu doesn’t require interpreting HashiCorp’s additional use grant at all.</p><h3>How Do You Decide Between OpenTofu and Terraform?</h3><p>The deciding factor tends to be existing platform commitment more than the license alone.</p><p><strong>Stay on or choose Terraform if:</strong></p><ul><li>You’re invested in HCP Terraform, need Stacks, or need enterprise support with an SLA</li><li>Your workflow depends specifically on Sentinel policies</li><li>You rely heavily on community resources, since the Terraform community remains significantly larger, meaning documentation, Stack Overflow answers, and tutorials are more abundant</li></ul><p><strong>Choose OpenTofu if:</strong></p><ul><li>You’re setting up a greenfield, self-managed environment and want open governance with no license ambiguity</li><li>You need state encryption, for_each support on provider blocks, or the -exclude flag now, without waiting on Terraform’s roadmap</li><li>You’re building internal tooling or a product on top of IaC and want zero licensing ambiguity</li></ul><h3>What If You Don’t Have to Choose?</h3><p>The framework above assumes a team has to commit to one binary. That assumption holds if your execution platform, state backend, and policy engine are all tied to a single tool. It stops holding if the platform underneath is tool-agnostic to begin with.</p><p>The real operational question isn’t “which binary do we standardize on?” It’s whether your governance layer, state management, and policy evaluation depend on that choice at all. If they do, switching tools later means rebuilding policy coverage from scratch. If they don’t, the choice between OpenTofu and Terraform becomes a per-workflow decision instead of an organization-wide bet.</p><h3>How Does StackGuardian Handle Both Terraform and OpenTofu?</h3><p>StackGuardian runs Terraform and OpenTofu as separate native Workflow types inside the same platform, not as two disconnected toolchains bolted together. Creating a Workflow through the wizard offers both as first-class options, each configured through the same four steps: Source and Parameters, Terraform Configuration, Deployment Environment, and version pinning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJD_1hjICuSugV5bmz0meg.png" /></figure><p>State management doesn’t fork by tool, even though the toggle carries the engine’s name. A Terraform Workflow has “Use Managed Terraform State” under Terraform Customizations; an OpenTofu Workflow has the equivalent “Use Managed OpenTofu State” under OpenTofu Customizations. Enabling either gives that Workflow the same centralized backend, with locking, versioning, and encryption handled identically regardless of which binary runs. A Terraform Workflow and an OpenTofu Workflow in the same Workflow Group both authenticate to that backend the same way, through the platform-managed connection rather than a separately configured backend block per engine.</p><p><strong>Version pinning happens per Workflow</strong>, not per platform. Each Workflow’s Terraform or OpenTofu Customizations panel includes a version selector, along with an optional Custom Tool Path for teams running a non-standard binary on a private runner. A team running OpenTofu 1.12 for new workflows and Terraform 1.10 for legacy ones pins each version at the Workflow level, no separate platforms or duplicated infrastructure required to keep both versions correct simultaneously.</p><p><strong>Policy evaluation is where the tool-agnostic design matters most.</strong> A Tirith or OPA policy scoped to a Workflow Group evaluates every Workflow inside that group, whether the underlying plan came from terraform plan or tofu plan. Since both tools produce a comparable plan structure, the same evaluator applies to both without a separate ruleset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4m8rn9Xzt8CGFAndAatPBA.png" /></figure><p>Tirith’s terraform_plan provider is documented specifically for Terraform and CloudFormation configurations. In practice, a policy written against this provider generally applies to an OpenTofu-produced plan too, since OpenTofu&#39;s plan JSON output is designed to stay compatible with Terraform&#39;s, but teams running mixed environments should verify evaluator behavior against their own OpenTofu plans rather than assuming full parity by default.</p><p>One thing worth planning for in a mixed fleet: Terraform and OpenTofu versioned independently after the fork, so a terraform_version string alone doesn&#39;t reliably tell a policy which engine actually produced a given plan; &quot;1.9&quot; means something different depending on which binary shipped it. Teams writing policies that need to treat the two engines differently, rather than identically, should scope that distinction explicitly at the Workflow or Workflow Group level rather than inferring it from a version number inside the plan.</p><p><strong>Drift detection, RBAC, and audit logging don’t fork by tool either.</strong> Automated Drift Check runs on the same schedule regardless of engine, RBAC controls who can create or modify Workflows of either type identically, and every action lands in the same Audit Logs, exportable to JSON or CSV, whether it came from a Terraform apply or an OpenTofu apply.</p><h3>Should You Run Both Terraform and OpenTofu at Once?</h3><p>Running both isn’t a compromise position; it’s the path many teams actually land on. Existing HCP Terraform workspaces stay where they are, since migrating live production state carries its own risk regardless of which tool it moves to. New workloads default to OpenTofu, where the license question doesn’t need revisiting for every new project.</p><p>Inside StackGuardian, that split doesn’t require two platforms or two credential sets. A Workflow Group can contain Terraform Workflows and OpenTofu Workflows side by side, governed by the same Policy Sets, the same RBAC, and the same Audit Logs. Running both tools stops being an operational burden and becomes a configuration choice made per Workflow, not per platform.</p><h3>Conclusion</h3><p>The OpenTofu fork stopped being a hedge or an experiment somewhere between the 2023 relicense and IBM’s 2025 acquisition of HashiCorp. By 2026, the two tools have genuinely different licenses, governance models, and feature sets, from client-side state encryption to provider iteration, and the decision between them is a real one for any team setting up new infrastructure or reevaluating an existing HCP Terraform commitment.</p><p>What matters more than the choice itself is whether the platform underneath forces that choice to be permanent. A team on a Terraform-only platform pays a real migration cost if the license or governance calculus changes later. A team on a platform that treats both tools as equally native keeps that decision reversible, workflow by workflow, without rebuilding state management or policy coverage from scratch.</p><p>Explore how<a href="https://stackguardian.io/"> StackGuardian</a> supports both engines under one policy and execution layer, or see the<a href="https://docs.stackguardian.io/"> StackGuardian documentation</a> for the full Workflow configuration reference.</p><h3>FAQs</h3><h3>1. Is OpenTofu a drop-in replacement for Terraform?</h3><p>For most workflows, yes. OpenTofu shares Terraform’s HCL syntax, provider protocol, and state model, so migration is usually swapping the binary rather than rewriting configuration. Teams depending on HCP Terraform-exclusive features like Stacks or Sentinel need a separate migration plan for those specific pieces.</p><h3>2. Does the Terraform BSL license affect internal use?</h3><p>No. The BSL doesn’t affect teams that simply run terraform apply against their own infrastructure. It restricts building a competitive offering sold to third parties that significantly overlaps HashiCorp&#39;s commercial products; internal use, including CI/CD pipelines, is permitted.</p><h3>3. What features does OpenTofu have that Terraform’s open-source CLI lacks?</h3><p>Native client-side state encryption, provider for_each for iterating provider blocks, early variable evaluation for backend configuration, and the -exclude flag. None of these are available in Terraform&#39;s open-source binary as of 2026.</p><h3>4. Can I run both Terraform and OpenTofu in the same organization?</h3><p>Yes. Many teams keep existing HCP Terraform workspaces in place while defaulting new projects to OpenTofu. On a platform like StackGuardian, both run as native Workflow types under the same Workflow Group, policy scope, and state management, so running both doesn’t require separate credentials or a second platform.</p><h3>5. Does StackGuardian support OpenTofu natively?</h3><p>Yes. OpenTofu is a native Workflow type alongside Terraform, CloudFormation, Ansible, Helm, and Kubectl, using the same Managed Terraform State backend and evaluated by the same Tirith or OPA policies regardless of which tool a given Workflow runs.</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/opentofu-vs-terraform"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb4a7535c36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform MCP Server: What It Is and How It Works | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/terraform-mcp-server-what-it-is-and-how-it-works-blog-stackguardian-498e62ad2cee?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/498e62ad2cee</guid>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 12:52:02 GMT</pubDate>
            <atom:updated>2026-11-19T12:52:02.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDGBEgj4W9pQNbE6FcEycA.png" /></figure><ul><li>MCP (Model Context Protocol) is an open standard that enables AI models to query live external tools and data rather than relying on frozen training data.</li><li>HashiCorp’s official Terraform MCP Server reached general availability on June 11, 2026, giving AI assistants direct access to provider docs, module details, Sentinel policies, and HCP Terraform or Terraform Enterprise workspace operations.</li><li>The server enforces existing Terraform authentication rather than handing agents credentials directly, and destructive operations like action_run or delete_workspace_safely stay disabled by default behind an explicit ENABLE_TF_OPERATIONS flag.</li><li>HashiCorp’s own documentation is direct about the risk: the server can expose Terraform data to whatever client queries it, so it isn’t meant to be paired with untrusted MCP clients or LLMs.</li><li>StackGuardian runs a separate, read-only MCP server focused on governance, drift status, policy evaluation results, and workflow health, which covers ground HashiCorp’s provisioning-focused server doesn’t reach.</li></ul><p>An AI coding assistant is only as good as the context it has. Ask one to write a Terraform resource for a database, and it answers based on whatever it learned during training, which might be a provider version from eighteen months ago or a resource argument that’s since been deprecated. It has no way to check. That’s the exact problem the Terraform MCP Server was built to close, and by mid-2026 it’s become one of the clearest examples of what a properly grounded AI assistant looks like for infrastructure work.</p><p>This post covers what MCP actually means for Terraform, how HashiCorp’s official server works under the hood, the operational and security trade-offs worth knowing before connecting it to anything, and how StackGuardian’s own MCP server addresses the governance side that HashiCorp’s provisioning-focused server doesn’t cover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gd-TLRvTVL8GuOTr7De1g.png" /></figure><h3>What Is MCP, and Why Does Terraform Need One?</h3><p>Model Context Protocol is an open standard that lets an AI model query external tools and data sources directly, rather than answering purely from what it learned during training. Instead of guessing, the model can ask a connected server for the current version of something and get back real, current data.</p><p>Terraform is a particularly good fit for this problem. Provider versions ship constantly, resource arguments get deprecated or renamed, and a module’s inputs can change between releases. An AI model’s training data is frozen at a point in time, but the Terraform Registry isn’t. Without a live connection, an assistant either hallucinates a plausible-looking but wrong configuration, or hedges everything with “you should double-check this,” which defeats the point of asking in the first place.</p><p>Connect the same assistant to a Terraform MCP server, and the difference becomes apparent immediately. Ask “how do I configure an AWS S3 bucket with versioning enabled,” and instead of reconstructing an answer from memory, the model queries the server, pulls the current provider documentation, and generates a resource block that matches what’s currently available.</p><h3>What Does HashiCorp’s Terraform MCP Server Actually Do?</h3><p>HashiCorp’s Terraform MCP Server reached general availability on June 11, 2026, and is an open-source project that connects AI assistants to the Terraform Registry, HCP Terraform, and Terraform Enterprise. It’s compatible with Cursor, Claude, Claude Code, Gemini, GitHub Copilot, and IBM Bob, among others.</p><p>The server organizes its tools into toolsets, each covering a distinct part of the Terraform ecosystem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaLHTgxkr4J7WiQ5HD1OFw.png" /></figure><p>Inside those toolsets, individual tools handle specific jobs. Provider tools like search_providers and get_provider_details pull resource, data source, and configuration documentation. Module tools like search_modules and get_module_details surface community- and verified-modules with their full inputs, outputs, and examples. Policy tools like search_policies and get_policy_details retrieve Sentinel policies for governance and compliance. A more recent addition, attach_policy_set_to_workspace, allows a governance workflow to be handled directly via a chat prompt rather than through the HCP Terraform UI.</p><p>The workspace-level tools go further than documentation lookup. list_workspaces, get_workspace_details, create_workspace, list_runs, get_run_details, and get_plan_json_output let an assistant actually inspect and, with the right flags enabled, act on real HCP Terraform or Terraform Enterprise infrastructure, not just answer questions about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFKBXAschVb9uRYD9b7i7Q.png" /></figure><p>Worth knowing before going further: StackGuardian also runs its own MCP server, built for a different job. Where HashiCorp’s server is oriented around writing and operating Terraform directly, StackGuardian’s is read-only and governance-focused, answering questions about drift, policy evaluation, and workflow health across a fleet rather than generating or applying infrastructure. The rest of this post covers HashiCorp’s server in depth first, then comes back to how StackGuardian’s approach differs later on.</p><h3>How Does the Terraform MCP Server Actually Connect to Your Infrastructure?</h3><p>Getting from “an AI assistant that answers questions” to “an AI assistant with live infrastructure access” comes down to a transport protocol and an authentication model.</p><p>The server supports two transports. stdio is the default, used for local development, where the MCP client and server communicate over standard input and output on the same machine. streamableHTTP, enabled by setting TRANSPORT_MODE=streamable-http, is built for remote and shared deployments, where a team runs one server instance that multiple developers&#39; assistants connect to over HTTP.</p><p>A typical local configuration, run through Docker, looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csUedoDCn3KD7ujet8VxLQ.png" /></figure><p>Authentication is handled by TFE_TOKEN and TFE_ADDRESS, which point the server to an existing HCP Terraform or Terraform Enterprise organization using a real API token. The server enforces whatever access that token already has, rather than granting the AI model some separate, broader permission set. If a token can&#39;t delete a workspace, neither can an assistant querying through it.</p><p>For a shared, remote deployment, the operational controls matter more. MCP_CORS_MODE (strict by default), MCP_ALLOWED_ORIGINS, MCP_RATE_LIMIT_GLOBAL, and MCP_RATE_LIMIT_SESSION all exist to keep a team-facing server from becoming an open door. Enabling OTEL_METRICS_ENABLED wires the server into OpenTelemetry, emitting tool-call counts, error rates, and call duration for monitoring, the same kind of observability a team would expect from any other production service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4PZ3e8T9tbVWlqqD3v5MA.png" /></figure><h3>What Are the Security Risks of Connecting AI to Live Terraform Data?</h3><p>HashiCorp is direct about this in its documentation: the MCP server can expose Terraform data to any client and model that requests it, and it explicitly should not be paired with untrusted MCP clients or LLMs. That’s a meaningfully different risk profile than a documentation lookup tool, since several of the server’s tools can read workspace configuration, variable values, and run logs, not just public provider docs.</p><p>The tools capable of actually changing infrastructure are locked down by default. action_run, which can apply or destroy a run, and delete_workspace_safely, which permanently removes a workspace, both stay disabled until an operator explicitly sets ENABLE_TF_OPERATIONS=true. Even with that flag enabled, create_run still defaults to safer run types like plan_only or refresh_state and only exposes auto_approve or is_destroy once operations are enabled. Nothing about the server ships apply-ready by accident.</p><p>That said, “read access” remains a meaningful exposure in its own right. A prompt injected into a malicious module’s README, or a compromised MCP client, could use read-only tools to enumerate workspace variables, pull run logs, or surface a private module’s internals, information that was never meant to leave the organization. The server’s rate-limiting and CORS controls reduce the blast radius of a misbehaving client, but they don’t substitute for restricting which clients can access a token in the first place.</p><h3>What’s Missing From HashiCorp’s MCP Server for Governance-Heavy Teams?</h3><p>HashiCorp’s server is built around two things: helping an assistant write correct Terraform and letting it operate directly against HCP Terraform or Terraform Enterprise workspaces. What it doesn’t natively expose is drift status, policy evaluation history across a fleet of workflows, or anything specific to the Terraform/OpenTofu-on-HCP world.</p><p>That gap matters for two kinds of teams. Ones running policy engines other than Sentinel don’t get the same query interface; the policy tools here are scoped to Sentinel policies specifically. And teams running infrastructure across multiple engines, Terraform alongside CloudFormation, Helm, or Ansible, don’t get one connective layer across all of it, since this server’s scope stops at the Terraform ecosystem.</p><p>This is exactly where a governance-focused MCP server earns its place alongside HashiCorp’s.</p><h3>How Does StackGuardian’s MCP Server Work?</h3><p>StackGuardian runs its own hosted MCP server, added in v1.31.4, connecting tools like Claude and ChatGPT directly to StackGuardian’s read-only APIs. Where HashiCorp’s server is oriented around writing and operating Terraform, StackGuardian’s is oriented around answering questions about what’s actually happening across a governed fleet of Workflows.</p><p>The difference shows up in the kinds of prompts each one is built to answer. A query like “why did workflow run #1247 fail” pulls from the same drift, compliance, and execution data the StackGuardian platform itself uses, no dashboard-hopping required to get an answer. “What’s the current status of all stacks in my organization” aggregates across every Stack in the org rather than one Workflow at a time. “Which workflows are still using template revision 2” surfaces exactly which deployments need updating before a rollout, and “assess the health of every workflow in this group before we ship” rolls up status across a whole Workflow Group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkKTHLRyhA6kuS1YJ7SbNw.png" /></figure><p>Because it’s read-only by design, the security posture is simpler than HashiCorp’s read/write model. There’s no ENABLE_TF_OPERATIONS-equivalent flag to worry about, since the server was never built to apply or destroy anything in the first place, only to answer questions about state that already exists.</p><p>The MCP server’s scope continues to expand, with more policy-as-code integrations and deeper multi-cloud coverage on the roadmap.</p><h3>Terraform MCP Server vs StackGuardian’s MCP Server: What’s the Actual Difference?</h3><p>These two aren’t competing for the same job. HashiCorp’s server is provisioning- and documentation-focused: it helps an assistant write correct Terraform using current provider and module data, and it can operate directly against HCP Terraform or Terraform Enterprise workspaces when explicitly enabled. StackGuardian’s server is governance- and observability-focused: providing read-only access to drift status, policy evaluation results, and execution health across Workflows and Stacks, regardless of which IaC engine produced them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4S1ZpSi1QY2sIKxZ08O6w.png" /></figure><p>A team running StackGuardian workflows on top of Terraform or OpenTofu can reasonably use both at once: HashiCorp’s server when writing new infrastructure code, StackGuardian’s server when asking what’s actually running, what’s drifted, and what’s waiting on approval.</p><h3>Conclusion: Where This Leaves Terraform and AI in 2026</h3><p>MCP servers are becoming the standard way for AI assistants to get grounded infrastructure context rather than guessing from stale training data, and Terraform’s ecosystem now has two distinct, complementary examples of what that looks like in practice. Which one matters for a given question depends on what’s actually being asked. “Help me write this resource block” is a HashiCorp MCP Server question. “Tell me what’s actually running and whether it’s compliant” is a StackGuardian MCP Server question.</p><p>Neither replaces the judgment of an engineer reviewing a plan before it is applied, and HashiCorp’s own security documentation is explicit that these tools shouldn’t be handed to an untrusted client without considering what they can read. But when grounded in real data rather than guesses, an AI assistant stops being a liability during infrastructure work and becomes genuinely useful.<a href="https://stackguardian.io/mcp"> Explore StackGuardian’s MCP integration</a> to see how it fits alongside your existing Terraform tooling.</p><h3>FAQs</h3><h3>1. Is HashiCorp’s Terraform MCP Server free to use?</h3><p>Yes, the Terraform MCP Server is open source, available on GitHub and as a Docker image. It’s free to deploy locally or as a shared team service; usage against HCP Terraform or Terraform Enterprise still requires an existing account and API token with the appropriate access.</p><h3>2. Can the Terraform MCP Server create or destroy infrastructure directly?</h3><p>Only if explicitly enabled. Tools like action_run and delete_workspace_safely are disabled by default and require the ENABLE_TF_OPERATIONS environment variable to be set to true. Even then, the server enforces whatever permissions the configured API token already has; it doesn&#39;t grant an AI model broader access than a human using the same token would have.</p><h3>3. What AI tools work with the Terraform MCP Server?</h3><p>HashiCorp lists Cursor, Claude, Claude Code, Gemini, GitHub Copilot, and IBM Bob as compatible clients, and any MCP-compliant client should be able to connect using either the stdio or streamableHTTP transport.</p><h3>4. Is it safe to connect an AI assistant to a production Terraform workspace via MCP?</h3><p>HashiCorp’s own documentation recommends caution: the server can expose Terraform data to the connected client and model, so it shouldn’t be paired with untrusted MCP clients or LLMs. Destructive operations are behind an explicit opt-in flag, but read access to workspace variables and run logs still represents a real exposure that should be restricted to trusted clients and scoped API tokens.</p><h3>5. Does StackGuardian’s MCP server work with tools other than Claude and ChatGPT?</h3><p>StackGuardian’s hosted MCP server is confirmed to connect Claude and ChatGPT directly to its read-only APIs. As with any MCP server, compatibility with additional clients depends on those clients supporting the standard MCP connection model.‍</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/terraform-mcp-server"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498e62ad2cee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IaC Security Best Practices: Policy in Terraform Workflows | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/iac-security-best-practices-policy-in-terraform-workflows-blog-stackguardian-07a123aaab03?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/07a123aaab03</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 12:53:16 GMT</pubDate>
            <atom:updated>2026-11-17T12:53:16.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5hdWKl2EOVxdD5yVMBC-Q.png" /></figure><ul><li>Shift-left security means catching misconfigurations at the point a Terraform plan is written, not after the resource is already running in production.</li><li>A clean terraform plan only confirms syntax and provider schema are correct; it says nothing about whether the resulting infrastructure is secure.</li><li>Real enforcement needs to run at three points: pre-commit, plan-time, and runtime, since each one catches a different class of problem the others miss.</li><li>Policy as code, through engines like Tirith and OPA, is what turns shift left from a checklist into something a pipeline actually enforces on every run.</li><li>StackGuardian builds policy evaluation directly into the workflow engine, so shift left enforcement isn’t a separate tool bolted onto the pipeline afterward.</li></ul><p>Security used to mean a review at the end of the pipeline: infrastructure got built, then someone with a checklist looked at it before it went live. Shift left moved that review earlier, catching problems at the point code gets written rather than after it’s deployed. Infrastructure as code is where this idea matters most, since a single misconfigured resource block in a shared module doesn’t create one insecure server; it can replicate that mistake across hundreds of resources the moment the plan is applied.</p><p>This post covers what shift left security actually requires for Terraform specifically, why a clean plan doesn’t guarantee a secure deployment, where policy enforcement needs to sit in the pipeline, and how StackGuardian builds that enforcement into the workflow engine itself rather than treating it as an add-on step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsN1ah1ZDC-qu2BexoJDZA.png" /></figure><h3>Shift Left Security in Infrastructure as Code</h3><p>Shift left security means catching a problem at the point of authorship or plan, not after the resource is already running. Applied to infrastructure as code, that means a misconfigured security group or an unencrypted storage bucket gets flagged while it’s still a block of HCL in a pull request, not after terraform apply has already created it.</p><p>The contrast with a traditional review model is mostly about timing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1h3aVbGAM4hwmZF3tXpGA.png" /></figure><p>Infrastructure as code raises the stakes of getting this wrong. A misconfigured module isn’t a single mistake; it’s a template. If that module gets reused across ten environments, the same open port or missing encryption setting exists in all ten the moment each one applies, and a traditional periodic audit might not catch the pattern until long after the tenth deployment.</p><h3>Why a Clean Terraform Plan Can Still Deploy Insecure Infrastructure</h3><p>terraform plan and terraform validate check two things: that the HCL syntax is correct, and that resource arguments match what the provider schema expects. Neither one evaluates whether the resulting infrastructure is secure. A plan can complete with zero errors and still describe a security group open to the entire internet, an S3 bucket with no encryption configured, or an IAM role with far more permission than the workload actually needs.</p><p>None of these are syntax problems. cidr_blocks = [&quot;0.0.0.0/0&quot;] is valid HCL. An aws_s3_bucket resource with no server_side_encryption_configuration block is a complete, plan-clean resource. Terraform&#39;s plan and validate commands were built to confirm a configuration will apply as written, not to judge whether what it applies is a good idea.</p><p>That gap is exactly what policy enforcement exists to close. Something has to sit between “this plan is syntactically valid” and “this plan is safe to apply,” evaluating the plan against rules that have nothing to do with HCL correctness and everything to do with what the infrastructure will actually expose once it’s running.</p><h3>Where Security Policy Needs to Run in a Terraform Pipeline</h3><p>No single checkpoint catches everything. Three distinct points in a pipeline each catch a different class of problem, and skipping any one of them leaves a real gap.</p><p><strong>Pre-commit and IDE-level checks</strong> run the fastest and catch the most obvious issues before code ever reaches a pull request. A linter or static analysis tool flagging an open security group as someone types it gives the cheapest possible fix, before a review, before a plan, before anything gets shared. What it misses is context: a pre-commit check evaluating a single file in isolation can’t see how that resource interacts with the rest of a live environment.</p><p><strong>Plan-time enforcement</strong> is the real gate. This is where a policy engine evaluates the actual terraform plan output, the full picture of what will change, against a defined ruleset before terraform apply runs. This catches what pre-commit checks miss, since it evaluates the complete plan rather than an isolated file, and it&#39;s the last point before infrastructure actually changes.</p><p><strong>Runtime and drift detection</strong> catches everything that bypassed the pipeline entirely: a manual console change, a resource created outside the approved workflow, or a policy violation introduced after the fact that the original plan never contained. This is the safety net for changes that never went through plan-time evaluation in the first place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97zFX5ulsr7QZdafBhkk9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgZRdVoB7VVVXvOrVhchpA.png" /></figure><h3>Policy as Code as the Enforcement Layer Behind Shift Left</h3><p>Policy as code means that security and compliance rules are written as structured, version-controlled files rather than as a document someone references manually. A rule lives in a repository, is reviewed through the same pull request process as any other code change, and is evaluated automatically by a pipeline rather than relying on someone to remember to check it.</p><p>Two engine types dominate this space today. OPA, using the Rego language, is a general-purpose policy engine that can evaluate the same rule across Terraform plans, Kubernetes manifests, and API requests, since it doesn’t care what kind of system is making the request. JSON-based frameworks like Tirith take a more structured approach, purpose-built for evaluating IaC plans specifically, without requiring a team to learn a dedicated policy language.</p><p>This is what actually makes shift left enforceable rather than aspirational. A checklist that depends on someone remembering to run it gets skipped the first time a deadline is tight. A policy engine wired into the pipeline evaluates every single plan, every time, with no dependence on anyone remembering anything.</p><h3>Writing Terraform Security Policies With Tirith and OPA</h3><p>A Tirith policy blocking a publicly open security group looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCtf4Jp1q09AkNbesf-3Rw.png" /></figure><p>Three parts do all the work here. meta sets which provider evaluates the plan, stackguardian/terraform_plan in this case. evaluators define the individual check, pointing at a specific resource type and attribute, with a condition that fails if the value matches an open CIDR block. eval_expression combines evaluator results using &amp;&amp;, ||, and !, letting a single policy require multiple checks to pass at once.</p><p>error_tolerance controls how the evaluator handles a resource that doesn&#39;t exist in a given plan. A value of 0 requires every field to be present and correct, or the policy fails outright. A value of 1 skips the evaluator entirely if the specified resource type isn&#39;t in the plan, rather than failing a plan that never touched a security group in the first place.</p><p>The same rule in OPA’s Rego looks structurally different but does the same job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AxgLnilHrp38sGExRTP-g.png" /></figure><p>Rego’s advantage shows up when the same rule needs to run somewhere other than a Terraform plan, a Kubernetes admission controller checking a NetworkPolicy for the same open-ingress pattern, for instance, using the same policy language and largely the same logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXEe3Gb67QGapVL8ah9w1Q.png" /></figure><h3>Enforcing Policy Without Blocking Every Deployment</h3><p>Setting every policy to hard-block on the first day is a common mistake. A brand-new policy running against months of existing infrastructure will surface false positives, edge cases the rule didn’t account for, and legitimate exceptions nobody thought to exempt. Blocking every deployment on day one either halts the team’s work entirely or results in the policy being disabled within a week out of frustration.</p><p>Graduated enforcement solves this. A policy can warn instead of block, logging a violation and notifying the team without stopping the deployment. It may require explicit approval, routing the plan to a named reviewer rather than blocking it or allowing it silently. Only once a policy’s false-positive rate is well understood does it make sense to switch it to a hard fail.</p><p>A reasonable rollout looks like this: enable a new policy in warn mode, review what it flags over one or two weeks, tune the rule against real false positives, then switch it to fail once the signal is clean. Skipping straight to fail with an unproven policy is how shift-left security earns a reputation for slowing teams down instead of protecting them.</p><h3>How StackGuardian Enforces Shift Left Security in Terraform Workflows</h3><p>StackGuardian runs two policy engines side by side rather than forcing a choice between them. Tirith, the JSON-based framework shown earlier, and native OPA support, sourcing Rego policies directly from a Git repository, both evaluate against the same Workflow.</p><p>Policies scope at three levels: organization-wide, a specific Workflow Group, or an individual Connector tied to a cloud account. This maps directly onto the graduated enforcement problem above: a new policy can be scoped to a single Workflow Group in warn mode while it’s being tuned, then widened to organization-wide once it’s proven, without touching production environments during the tuning period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIWxPb7JH6bzr_0EuYaU1A.png" /></figure><p>Enforcement itself splits into two distinct stages that mirror the pipeline framework covered earlier. <strong>Configuration Rules</strong> evaluate at workflow creation, update, or runtime, functioning as the plan-time gate: if a Configuration Rule fails, the run is blocked immediately; if it passes or issues a warning, execution proceeds to <strong>Runtime Rules</strong>, which evaluate during actual execution. Each rule carries one of five statuses, Pass, Fail, Warn, Approval Required, or Unevaluated, giving the graduated enforcement model from the previous section a concrete mechanism rather than just a policy.</p><p>The runtime leg of shift left doesn’t stop once a resource is deployed. Automated Drift Check runs on a schedule per workflow, catching exactly the class of problem that plan-time enforcement structurally can’t: a resource changed manually outside the pipeline entirely; the same gap runtime and drift detection exists to close in any shift left model.‍</p><p>Writing every policy by hand isn’t required to get started. The Policy Marketplace has 250+ pre-built templates covering CIS benchmarks, PCI DSS, tagging requirements, and encryption enforcement, which can be subscribed to directly rather than authored from scratch. And every policy evaluation, whether it passed, failed, or triggered approval, lands in Audit Logs, exportable as JSON or CSV, which turns shift-left enforcement into something a compliance review can actually verify happened.</p><h3>A Shift-Left Pipeline From Commit to Drift Check</h3><p>Put the whole framework together, and the pipeline looks like this: a pre-commit check flags an obvious issue before the pull request opens. The plan runs, and Configuration Rules evaluate it against Tirith or OPA policies scoped to the relevant Workflow Group, blocking outright on a hard failure or routing to a named approver on a flagged one. Once approved and applied, Runtime Rules continue evaluating during execution. After the resource is live, Automated Drift Check runs on a schedule, catching any changes outside the pipeline going forward.</p><p>Every stage in that sequence maps to one of the three enforcement points covered earlier, pre-commit, plan-time, runtime, with nothing left as a manual step someone has to remember. That’s the practical difference between a security checklist and a shift-left pipeline: one depends on discipline, the other runs the same way every time regardless of who’s under deadline pressure that week.</p><h3>Conclusion</h3><p>Shift left security isn’t a single tool or a single checkpoint; it’s a description of where enforcement happens across a pipeline: as early as authorship, confirmed again at plan time, and backstopped by runtime detection for anything that slips past both. Terraform’s own plan and validate commands were never built to make that judgment, which is exactly the gap that policy-as-code exists to close.</p><p>What makes the difference between shift left as a slide in a security review deck and shift left as something a team actually gets is whether the enforcement runs automatically on every plan, without anyone having to remember to trigger it. StackGuardian’s Tirith and OPA support, mapped onto Configuration Rules, Runtime Rules, and Automated Drift Check, builds that enforcement directly into the workflow engine rather than treating it as a separate tool.<a href="https://stackguardian.io/"> Explore StackGuardian’s policy engine</a> to see how the three enforcement points fit into a real pipeline.</p><h3>FAQs</h3><h3>1. What’s the difference between shift left security and traditional security reviews?</h3><p>Traditional security reviews happen after infrastructure is already deployed, often during a periodic audit weeks or months later. Shift-left security moves that check at the point of authorship or planning, catching a misconfiguration before it ever reaches production rather than remediating it after the fact.</p><h3>2. Can Terraform’s own validate and plan commands catch security misconfigurations?</h3><p>No. terraform validate and terraform plan confirm HCL syntax is correct and that resource arguments match the provider schema. Neither one evaluates whether the resulting infrastructure is secure; an open security group or an unencrypted bucket can pass both commands cleanly, since neither was built to make that judgment.</p><h3>3. Should security policies block every deployment or just warn?</h3><p>Neither, universally. New policies should start in warn mode to surface false positives without halting work, then graduate to a hard block once the false-positive rate is well understood. A policy that blocks every deployment from day one, before it’s been tuned, tends to get disabled out of frustration rather than fixed.</p><h3>4. How does StackGuardian decide whether a policy violation blocks a deployment or just warns the team?</h3><p>Each policy rule has two configurable outcomes: an action when it passes and an action when it errors, with five possible statuses: Pass, Fail, Warn, Approval Required, or Unevaluated. A team sets this per rule, so a tagging violation can log a warning and continue while a production security group change blocks outright or routes to a named approver.</p><h3>5. Can StackGuardian’s drift detection catch a security misconfiguration introduced outside Terraform entirely?</h3><p>Yes, that’s specifically what Automated Drift Check is for. A resource changed manually through a cloud console, outside any Terraform workflow, never goes through plan-time policy evaluation, since that evaluation only runs against changes the pipeline sees. Drift Check runs on a schedule against the live resource, independent of how it changed, closing that gap.</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/shift-left-security"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07a123aaab03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Query: What It Is and How It Works | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/terraform-query-what-it-is-and-how-it-works-blog-stackguardian-309f2673b8cc?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/309f2673b8cc</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 11:25:50 GMT</pubDate>
            <atom:updated>2026-11-12T11:25:50.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlqJLBcE33cJak8FArK2nw.png" /></figure><ul><li>terraform query is a native CLI command for discovering infrastructure that exists in the cloud but isn&#39;t tracked in Terraform state.</li><li>It shipped in Terraform 1.14, generally available on November 19, 2025, built around a new list block and .tfquery.hcl files kept separate from the regular plan graph.</li><li>The workflow runs in two steps: discover matching resources with terraform query, then optionally generate importable configuration with the -generate-config-out flag.</li><li>The real limitation is provider support. A provider has to implement list resource support before terraform query works against it, and it isn&#39;t available in OpenTofu yet.</li><li>StackGuardian’s SGCode solves the same underlying problem: unmanaged infrastructure outside code, across multiple clouds, without waiting for a provider to add support first.</li></ul><p>Every Terraform user eventually encounters infrastructure that exists in the cloud but isn’t in Terraform state. Someone provisioned a resource through the console during an incident, a script ran once and was never checked in, or an account was inherited from an acquisition with no documentation. Until recently, finding that infrastructure meant either manually clicking through a cloud console or writing a one-off script to cross-reference resource IDs, since Terraform had no native way to ask, “What’s actually out there that I don’t already know about?”</p><p>This post covers what terraform query discovers, how the underlying list block and .tfquery.hcl files work, where the feature still falls short, and how StackGuardian&#39;s SGCode approaches the same discovery problem from a different angle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jb7BxnkpJWIu9WJAEhWJow.png" /></figure><h3>What Terraform Query Discovers</h3><p>terraform query is a native command that searches real, running infrastructure for resources matching defined criteria, without requiring that infrastructure to already exist in Terraform state or configuration. It answers a question Terraform previously had no built-in way to ask: what&#39;s running in this account that isn&#39;t managed here yet.</p><p>HashiCorp built this specifically to address a familiar set of problems that accumulate as cloud environments scale: wasted spend on resources nobody’s tracking, configuration drift on things nobody’s watching, missing policy coverage for anything outside state, and shadow infrastructure that surfaces during an incident rather than a planned review. Before this feature existed, closing that gap meant either the older terraform import command run on one resource at a time, or third-party tools built specifically to fill the void, since Terraform itself had no discovery mechanism of its own.</p><h3>How the List Block and .tfquery.hcl Files Work</h3><p>Query definitions live in files with the .tfquery.hcl extension and are deliberately kept separate from regular .tf configuration. That separation isn&#39;t incidental: list operations are read-only and exploratory by nature, and mixing them into the normal plan graph would blur the line between &quot;here&#39;s what I&#39;m declaring&quot; and &quot;here&#39;s what I&#39;m looking for.&quot;</p><p>A query file defines one or more list blocks, each specifying a resource type to search for and the criteria to search by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*sjCtpqOpDoXBb_zjYmrsSA.png" /></figure><p>Running terraform query in a directory containing this file checks for every .tfquery.hcl file present, queries the relevant provider&#39;s API for matching resources, and prints the results to the terminal. Nothing changes in state at this point; the command only looks and reports.</p><p>The more useful step comes with the -generate-config-out flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Cdktj8DUkJqpL3EFwLtQSA.png" /></figure><p>This writes a new file containing both import blocks and the corresponding resource blocks needed to bring the discovered infrastructure under management. Review and commit that generated file, then run terraform apply as usual, to pull the resources into state. Nothing gets imported automatically just by running the query.</p><p>For scripted or CI-driven use, the -json flag switches the output to machine-readable JSON instead of the default human-readable text, which is useful for piping results into another tool rather than reading them directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJLTZI2dUjxbHwpWAizXfw.png" /></figure><h3>Where Terraform Query Still Falls Short</h3><p>The feature is genuinely useful, but it has real boundaries worth knowing before relying on it.</p><p><strong>Provider support isn’t universal.</strong> A provider has to explicitly implement list resource support before terraform query works against it at all. This isn&#39;t a hypothetical gap; running a query against a resource type the provider hasn&#39;t implemented returns an explicit error rather than an empty result, as confirmed in an open GitHub issue against the GitHub provider itself, which still doesn&#39;t support list resources for something as basic as organization membership.</p><p><strong>It’s Terraform-only.</strong> OpenTofu doesn’t have an equivalent command yet. A feature request tracking this ( opentofu/opentofu#3787) remains open and unimplemented as of this writing, tagged &quot;pending-decision,&quot; meaning teams standardized on OpenTofu don&#39;t get this discovery capability right now.</p><p><strong>Each query is scoped to one provider at a time.</strong> No built-in mechanism lets a single query aggregate results across AWS, Azure, and GCP simultaneously. A multi-cloud discovery effort involves running separate queries for each provider and manually reconciling the results, since the tool itself doesn’t cross provider boundaries.</p><h3>How StackGuardian Approaches the Same Discovery Problem</h3><p>terraform query and StackGuardian&#39;s SGCode are solving the same underlying problem, infrastructure that exists but isn&#39;t managed, from different starting points. terraform query is a CLI command scoped to any provider that implements list support. SGCode is a platform capability built specifically to discover and codify unmanaged infrastructure as an ongoing practice, not a one-off command.</p><p>SGCode’s Cloud Inventory connects directly to AWS, Azure, and GCP accounts and discovers every resource across the environment in a single pass, cross-referencing its findings against connected state backends to determine what’s already covered and what isn’t. That cross-cloud reach doesn’t depend on any individual provider having implemented a specific list resource type, since SGCode isn’t working through Terraform’s provider plugin interface the way terraform query does.</p><p>Where -generate-config-out produces import and resource blocks for a human to review, SGCode&#39;s AI-powered codification does something comparable but goes further: it generates the Terraform or OpenTofu configuration, resolves dependencies between the discovered resource and anything it references, and validates the output through an internal plan run before proposing anything, publishing the result as a pull request to a connected Git repository rather than a local file waiting to be reviewed and applied manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LU8yUfYq57R0-dPSXc7yw.png" /></figure><p>None of this makes terraform query redundant. They sit at different layers: one is a CLI primitive inside Terraform itself, scoped to whatever a given provider supports; the other is a platform capability designed to run continuously across a multi-cloud estate regardless of provider-level implementation status.</p><h3>When Each Approach Makes Sense</h3><p>terraform query fits a team already deep in the Terraform ecosystem, working with a provider that has implemented list support, doing a scoped, one-off discovery task, finding untagged EC2 instances in a specific account, for example, where the CLI workflow is fast, and the provider gap doesn&#39;t matter.</p><p>SGCode fits ongoing, cross-cloud discovery as a continuous practice rather than a single task, especially in brownfield environments with years of unmanaged infrastructure across multiple cloud accounts, where waiting on provider-by-provider list-resource support isn’t a realistic workaround.</p><p>These aren’t mutually exclusive. A team could reasonably use terraform query for a quick, scoped AWS discovery task while relying on SGCode for broader, ongoing coverage tracking across every cloud account the organization runs.</p><h3>Conclusion</h3><p>terraform query is a real step forward for a problem that used to require manual console work or a third-party tool bolted onto Terraform. The list block and .tfquery.hcl file design are genuinely well thought out, keeping discovery cleanly separate from the regular plan graph. But it&#39;s early, provider support is inconsistent, and it doesn&#39;t exist in OpenTofu at all yet.</p><p>The underlying problem, infrastructure existing outside code, isn’t new, and it isn’t solved by any single command. StackGuardian’s SGCode treats it as a continuous practice rather than a one-off CLI action: cross-cloud by default, without depending on any individual provider implementing list support first.<a href="https://stackguardian.io/"> Explore how SGCode discovers and codifies unmanaged infrastructure</a> alongside whatever Terraform-native tooling a team already relies on.</p><h3>FAQs</h3><h3>1. What is the terraform query used for?</h3><p>terraform query discovers infrastructure resources that exist in the cloud but aren’t currently tracked in Terraform state or configuration. It finds unmanaged resources, audits what’s running against what’s declared in code, and can optionally generate the configuration needed to bring those resources under management.</p><h3>2. Does terraform query work with every Terraform provider?</h3><p>No. A provider must explicitly implement list resource support before a terraform query can discover resources of that type. Providers that haven’t implemented it, the GitHub provider is a confirmed example, return an explicit error rather than results when queried.</p><h3>3. Is terraform query available in OpenTofu?</h3><p>Not yet. A feature request tracking equivalent functionality remains open on OpenTofu’s repository and is marked pending-decision as of this writing, so teams running OpenTofu don’t currently have a native equivalent to this command.</p><h3>4. How does StackGuardian’s SGCode differ from terraform query for discovering unmanaged resources?</h3><p>SGCode discovers resources across AWS, Azure, and GCP in a single platform, without depending on any individual provider having implemented list resource support the way terraform query requires. It also goes further than discovery, generating and validating Terraform or OpenTofu configuration for what it finds and publishing the result as a pull request, rather than producing a local file for manual review and apply.</p><h3>5. Can terraform query results be automatically imported into Terraform state?</h3><p>Not automatically from the query itself. Running a terraform query with the -generate-config-out flag produces a file containing import and resource blocks, but nothing changes in state until that generated configuration is reviewed and terraform apply is run against it.‍</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/terraform-query-what-it-is-and-how-it-works"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=309f2673b8cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Checkov and Tirith: Govern Every IaC Pipeline | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/checkov-and-tirith-govern-every-iac-pipeline-blog-stackguardian-2024b9a20ce0?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2024b9a20ce0</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devsecops]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 12:26:49 GMT</pubDate>
            <atom:updated>2026-11-10T12:26:49.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3reS9PAKy_O0pzghJbZYuA.png" /></figure><ul><li>Many IaC pipelines already run a security scanner such as Checkov. The rules specific to your organisation, such as required tags, cost limits and team conventions, still need an owner and a way to be enforced.</li><li>Tirith is StackGuardian’s open-source policy engine for those rules. You write them as declarative JSON and evaluate them against Terraform plans, Infracost estimates, Kubernetes manifests and workflow files.</li><li>Connecting a pipeline takes one step after terraform plan: the Tirith GitHub Action, the Tirith GitLab CI/CD component or a Tirith Bitbucket Pipelines step.</li><li>Once connected, StackGuardian runs Tirith, Checkov and other policy engines such as Wiz on plans and code artifacts, keeps every result for audit, and reports the pipelines that skip the checks.</li><li>The platform adds plan visualisation, continuous enforcement, approvals, credential brokering, run snapshots, drift detection, recovery, notifications, SG Code modernisation and AI remediation with Kyro, including turning a finding into a Tirith policy.</li></ul><p>Most platform teams already scan their infrastructure code, often with Checkov. Over time they find a second category of rule that a generic scanner was never meant to own: the operating conventions of their own organisation. Who owns this resource? Does this change fit the budget? Is every repository enforcing the same version of the rule, and can anyone prove it?</p><p>This post covers how Tirith turns those rules into policy as code, how to connect the pipelines you already run to StackGuardian with a single step, and what the platform does with every plan once it can see them. Product status was checked on 1 October 2026 against Tirith 1.2.1 and the documentation linked at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJcaDY-Rju691oDe_u6npQ.png" /></figure><h3>Where Security Scans Leave Gaps</h3><p>An encrypted, private bucket can still lack the ownership tag your incident process depends on. A technically valid plan can exceed the monthly cost limit your finance partner agreed. A team can run the right checks in one repository while another repository runs a copy of the policy that was last updated a year ago.</p><p>These are governance problems that sit alongside security scanning, and each one is specific to how your organisation operates. Solving them takes three things: a clear way to write your own rules, a reliable way to run them on every change, and a record that shows they ran.</p><h3>Tirith: Your Own Rules as Policy as Code</h3><h4>Rules That Are Easy to Write and Review</h4><p>Tirith gives policy authors one consistent JSON structure: choose a provider, select the value or operation, then state the condition. The beta interface in Tirith 1.2.1 helps you build policies, experiment in a playground and inspect the resource behind a failure, and lint catches an invalid policy structure before you need a plan. Reviewers read a policy the same way every time, which keeps rule changes quick to approve.</p><h4>One Policy Approach Across Documents</h4><p>Infrastructure decisions involve more than a Terraform plan. They involve an Infracost estimate, a Kubernetes manifest or a CI workflow definition. Tirith supplies providers for each, so a plan policy can require an ownership tag while a separate cost policy checks an Infracost total, both written the same way. A single rule that joins several documents is still roadmap work.</p><h4>Policies Owned Centrally</h4><p>A policy file copied into fifty repositories drifts into fifty versions. With platform mode, tirith platform check evaluates the same plan against the policies your StackGuardian organisation enforces, with the same verdicts and exit codes. Policy owners change a rule once, and every connected pipeline picks it up on its next run.</p><h3>A Small Starting Point</h3><p>Install Tirith 1.2.1 from the pinned Git tag documented in the repository. The bare PyPI package named tirith is a different project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OxGd6u-1U3MlWoqvmGqlA.png" /></figure><p>A minimal plan policy that requires an owner tag, adapted from the example in Tirith’s policy-authoring skill. Test it against a plan that should pass and one that should fail before you rely on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRUDtE6CZJ8WNHQU80TuFg.png" /></figure><p>To try it locally, place the check between plan and apply. This sequence stops on any error and applies the saved binary plan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DA6ob7Ejij3L3CrM9-n5ZA.png" /></figure><p>Treat plan artifacts as sensitive. Tirith does not yet provide built-in plan identity verification, so make sure apply uses the exact plan that was evaluated and protect the required checks in CI.</p><h3>Connect Your IaC Pipeline in One Step</h3><p>You do not need to rebuild your pipelines to bring them under governance. Add one step after terraform plan in the CI system you already use, and the plan flows to Tirith and StackGuardian. Existing apply jobs stay where they are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXIjGrP1H4BSGKuvfZ5OYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4do4la53RDLTzvvcJ9sLaA.png" /></figure><p>Every route works in local mode first, evaluating policy files committed to the repository. Switch the same step to platform mode when you want StackGuardian to own the policies, run the other engines and keep the evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZdBYazCqeQYfvNw2sTjAA.png" /></figure><h3>What StackGuardian Adds Once Your Pipeline Is Connected</h3><p>StackGuardian runs Tirith, Checkov and other policy engines you already rely on, such as Wiz, on plans and code artifacts. It keeps every result, links it to the run that produced it, and makes it available for audit and for remediation through Kyro AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asp1Xw_4_0i4CDyq6y0mLw.png" /></figure><p>Some of these depend on how far you connect the platform. Approvals, credential brokering, drift, recovery and snapshots need the relevant workflow, permissions and state or execution connection, which you configure separately from installing the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yoMB4VHCQtG1ZslyYvbqAg.png" /></figure><h3>From Finding to Guardrail With Kyro</h3><p>A finding fixed once can return in the next pull request. Kyro, the AI assistant in StackGuardian, closes that loop. When a scan, a policy result or detected drift raises a finding, Kyro drafts a Tirith policy against the real schema, together with a proposed fix for the code that caused it. Your team reviews the policy with passing and failing tests, approves it, and StackGuardian enforces it on every connected pipeline, so the same mistake is stopped in the next plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDz7zaST5u7dunDL6KGsGw.png" /></figure><p>People stay in control of every step that changes something. Kyro proposes; a person approves; the deterministic Tirith evaluator decides whether a change passes. The StackGuardian MCP server gives authorised agents the same context, including workflows, templates, policy attachments and run information.</p><h3>Conclusion</h3><p>Your scanners already check that resources are secure. Tirith gives you a declarative, reviewable way to enforce the rules that only your organisation cares about, across plans, cost estimates, Kubernetes and workflow files. StackGuardian runs those rules and the engines you already use on every pipeline, keeps the evidence, shows you where checks are missing, and uses Kyro to turn each new finding into a guardrail.</p><p>Start with the rule your engineers still check by hand. <a href="https://github.com/StackGuardian/tirith">Try Tirith on that rule</a> in one pipeline, or <a href="https://www.stackguardian.io/book-call">connect your pipeline with a StackGuardian engineer</a> and see every plan, policy result and coverage gap in one place.</p><h3>FAQs</h3><h3>1. Do we need to change our existing security scanners to use Tirith?</h3><p>No. Tirith runs as an additional step in the pipeline you already have, so your current checks keep running as they are. Once the pipeline is connected, StackGuardian can run Checkov and other policy engines alongside Tirith and keep all of their results in one place.</p><h3>2. Can StackGuardian run Checkov and other policy engines?</h3><p>Yes. StackGuardian runs Tirith, Checkov and other policy engines such as Wiz on plans and code artifacts. You can enforce every Checkov check or only selected rules, control them centrally, keep the results for audit and remediation, and see which pipelines are not applying them.</p><h3>3. Do we have to move CI or buy StackGuardian to use Tirith?</h3><p>No. Tirith’s local evaluator is Apache-2.0 and works without an account. Platform mode is optional and evaluates against your StackGuardian organisation. Existing apply jobs can stay in place.</p><h3>4. Which CI systems can we connect?</h3><p>GitHub Actions through the <a href="https://github.com/StackGuardian/tirith-iac-governance-action">Tirith IaC governance action</a>, GitLab CI/CD through the Tirith CI/CD component ( <a href="https://gitlab.com/stackguardian/tirith-component-demo">demo project</a>), and Bitbucket Pipelines through a Tirith step ( <a href="https://bitbucket.org/__refeed__/tirith-bitbucket-demo/src/main/">demo repository</a>). Other container-based CI systems can call the Tirith CLI directly after the plan step.</p><h3>5. Does an “approval required” result stop an external CI job?</h3><p>No. Through the CI integration today, an approval-required result is reported as a warning, so the CI job continues. Where a human decision must block the change, use your CI’s own approval gate or a StackGuardian workflow with approvals configured.</p><h3>6. Does using Kyro or other AI agents change the security model?</h3><p>No. Human-authored and agent-authored changes pass through the same configured gate. Kyro drafts policies and proposes fixes, a person approves them, and deterministic evaluation decides whether a change passes. Each tool can only vouch for the checks and inputs it actually evaluates.‍</p><h3>Availability and Sources</h3><p>Checked on 1 October 2026. Tirith 1.2.1 is the latest stable release; it includes the beta interactive interface, lint and format commands and richer result context. Still in development: predefined policy packs (PR #364), PyPI publishing (PR #284), native YAML policy authoring, mixed-provider and multi-document rules, plan identity verification and external CI approval coordination. Treat open PRs and issues as work in progress until they ship. Platform capabilities depend on your StackGuardian plan, configuration and connected workflows; check availability for your deployment.</p><ul><li><a href="https://github.com/StackGuardian/tirith/releases/tag/1.2.1">Tirith release 1.2.1</a></li><li><a href="https://github.com/StackGuardian/tirith">Tirith repository and usage</a></li><li><a href="https://github.com/StackGuardian/tirith/blob/main/docs/platform-check.md">Tirith platform check reference</a></li><li><a href="https://github.com/StackGuardian/tirith-iac-governance-action">Tirith GitHub Action</a></li><li><a href="https://gitlab.com/stackguardian/tirith-component-demo">Tirith GitLab CI/CD component demo</a></li><li><a href="https://bitbucket.org/__refeed__/tirith-bitbucket-demo/src/main/">Tirith Bitbucket Pipelines demo</a></li><li><a href="https://github.com/StackGuardian/tirith/blob/main/.claude/skills/tirith-policies/SKILL.md">Tirith policy-authoring skill</a></li><li><a href="https://stackguardian.github.io/tirith/at-scale/">Tirith at scale</a></li><li><a href="https://docs.stackguardian.io/docs/mcp-server/">StackGuardian MCP server documentation</a></li><li><a href="https://www.checkov.io/1.Welcome/What%20is%20Checkov.html">Checkov overview</a></li></ul><p>Related reading: <a href="https://www.stackguardian.io/post/shift-left-security">IaC security best practices: policy enforcement in Terraform workflows</a> and <a href="https://www.stackguardian.io/post/terraform-mcp-server">Terraform MCP Server: what it is and how it works</a>.</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/checkov-and-tirith-where-each-fits"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2024b9a20ce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Import: How It Works and Where It Falls Short | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/terraform-import-how-it-works-and-where-it-falls-short-blog-stackguardian-ef179805bc3c?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef179805bc3c</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 11:26:13 GMT</pubDate>
            <atom:updated>2026-11-05T11:26:13.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsCymBJMRwNJsf8y0HD3zA.png" /></figure><ul><li>Terraform import brings a resource that already exists in the cloud into Terraform’s state file, without creating, destroying, or modifying that resource in the process.</li><li>The classic command only ever touches state. It never writes the matching .tf configuration, so that step stays manual. A configuration that doesn’t match what got imported can quietly plan a destroy-and-recreate on the next run.</li><li>Terraform 1.5 introduced import blocks and the -generate-config-out flag, turning import into a two-part workflow: a declarative, reviewable block plus generated configuration a human still has to check.</li><li>Even with those additions, import remains scoped to resources a team already knows exist. It has no discovery mechanism of its own, so someone still has to supply the resource ID and type before anything happens.</li><li>StackGuardian’s SGCode addresses the piece import was never built for: finding unmanaged infrastructure across AWS, Azure, and GCP in the first place, then generating and validating the configuration for what it finds.</li></ul><p>Every team running Terraform at any real scale eventually runs into the same problem: infrastructure exists that Terraform doesn’t know about. Someone provisioned a resource through the console during an incident and never circled back. An account came in through an acquisition with no code to show for it. A script ran once, years ago, and nobody wrote the equivalent .tf file afterward. Terraform’s state file only tracks what it was told to track. The gap between what is running and what state describes is a common source of drift, duplicate resources, and failed plans.</p><p>terraform import has been the standard answer to that gap since early Terraform versions, and it’s still the command most people reach for first. This post covers what the classic import command does and does not do. It then explains how import blocks and generated configuration changed the workflow in Terraform 1.5, and which limitations remain. The last section shows how StackGuardian’s SGCode approaches the same unmanaged-infrastructure problem from a different starting point.</p><h3>What Terraform Import Does and Why Teams Need It</h3><p>Terraform’s state file is the source of truth it uses to map real infrastructure back to configuration. Every resource block in a .tf file corresponds to an entry in state, and every plan Terraform runs works by comparing that state against both the configuration and the actual state of the world. When a resource exists in the cloud but has no corresponding entry in state, Terraform can’t know about it. It won’t show up in a plan, it won’t get tracked for drift, and if someone eventually writes a resource block that happens to describe it, Terraform will try to create a duplicate rather than recognizing the two as the same thing.</p><p>terraform import closes that gap. It takes a resource that already exists, such as an S3 bucket, a security group or a virtual machine. It then writes an entry for that resource into the state file, which associates a real cloud resource ID with a Terraform resource address. Nothing about the resource itself changes. No API call creates, modifies, or destroys anything in the cloud account. The only thing that changes is Terraform’s own bookkeeping, moving a resource from “outside state” to “inside state” without touching what’s actually running.</p><p>Import solves exactly one problem, which is getting a resource’s identity into state. It was never designed to write the configuration that describes that resource, and for most of Terraform’s history it didn’t try to.</p><h3>How the Classic Terraform Import Command Works</h3><p>The original import workflow runs as a single CLI command against a resource address and a real-world resource ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*22zcvyBsh5Bv_GSfEfhXfw.png" /></figure><p>Here, aws_security_group.web is the resource address as it would appear in a .tf configuration, and sg-0a1b2c3d4e5f67890 is the actual security group ID from AWS. Running this command does exactly one thing: it writes a state entry linking that address to that ID.</p><p>Critically, this command has always required the resource block to already exist in the configuration, even as an empty placeholder, before the import runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*gYkEBsNXBGxlGnl8utplVg.png" /></figure><p>Once the import completes, running terraform plan immediately afterward shows the real gap in this workflow. The .tf file above defines no attributes, so Terraform&#39;s plan shows a long list of changes it thinks it needs to make. Nothing is wrong with the resource; the configuration simply doesn&#39;t describe its real settings yet. The person running the import has to manually inspect the resource, usually via terraform state show aws_security_group.web or the cloud console directly, and hand-write a configuration block that matches every attribute Terraform cares about. Only once that configuration matches does a plan come back clean.</p><p>This is the core weakness of the classic command: state and configuration can drift apart the moment the import finishes, and nothing catches that automatically. A wrong CIDR block, a missed tag or an attribute left at its default value shows up as an unexpected change in the plan. If the attribute forces replacement, that change becomes a destroy-and-recreate.</p><h3>Resource Addressing Gets More Complicated Inside Modules and Loops</h3><p>The examples above assume a flat, top-level resource, but real configurations rarely stay that simple, and the classic command’s addressing syntax has to account for modules, count, and for_each at the exact moment of import.</p><p>A resource declared inside a child module needs its full module path in the address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*aL_xOtikRmRAnoIlD6rYUg.png" /></figure><p>A resource declared with count needs its numeric index in square brackets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*H_sbjE35jx3ik1CDKMaidA.png" /></figure><p>And a resource declared with for_each needs its map key, quoted, inside the brackets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*0HsF_OJhZGh5uSZC97JSoA.png" /></figure><p>Shells often need the whole address quoted because square brackets have special meaning to most shells; missing the quotes is a common source of “resource not found” errors that have nothing to do with the resource ID itself. Getting the address wrong doesn’t always fail loudly. In some cases it silently imports into the wrong instance of a count or for_each resource, which then surfaces later as a confusing plan rather than an immediate error.</p><h3>Import Blocks and Config Generation: What Changed</h3><p>Terraform 1.5 introduced a meaningfully different way to run imports: the import block, written directly in .tf configuration rather than issued as a one-off CLI command. Paired with the -generate-config-out flag, this turned import from &quot;write state, then manually reverse-engineer config&quot; into &quot;declare an intent to import, and let Terraform draft the configuration for you.&quot;</p><p>An import block looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*p8JF0R2fPl-knzNiwC5D6g.png" /></figure><p>Rather than running immediately like the CLI command, this block is evaluated the next time a plan runs. Combined with -generate-config-out, the plan step does something the classic command never could:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*BjqAtAnMnKv9PgL5aAe0xA.png" /></figure><p>This produces a new file, generated.tf, containing an actual resource block populated with the real attributes Terraform found on the existing security group, rather than the empty placeholder the classic workflow required a person to fill in by hand. The generated file is meant to be reviewed, cleaned up, and folded into the rest of the codebase, not applied blindly. Sensitive values, computed attributes, and anything the provider can&#39;t safely infer are typically left incomplete or commented, and a careful review is still the step that catches whether the generated block actually matches intent.</p><p>Two limits are worth knowing up front. HashiCorp shipped config generation as experimental in Terraform 1.5, and the plan command’s documentation still labels it experimental. It is also described as a root-module option, so an import block that targets a resource inside a child module may still need its configuration written by hand.</p><p>The practical shift is real: instead of a person manually transcribing every attribute off a console screen, Terraform generates a first draft, and the human’s job moves from writing configuration from scratch to reviewing and correcting a draft that’s usually most of the way there. That’s a meaningfully lower-effort and lower-error workflow than the classic command, particularly for resources with many attributes.</p><p>To see why that matters, it helps to look at what “matching configuration” actually requires for a resource with more than a couple of settings. An S3 bucket with versioning and server-side encryption enabled isn’t just a bucket name; it’s a nested set of sub-resources that all have to agree with what’s actually configured in AWS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLHi3OFBEalcVh8tVAtQEg.png" /></figure><p>In both workflows, each of these three resources needs its own import, run against its own resource ID, because versioning and encryption are modeled as separate resources tied to the bucket rather than attributes on the bucket itself. Config generation doesn’t find the sub-resources for you. Someone still has to know they exist and write an import block for each one. Getting an enum value like sse_algorithm slightly wrong produces a plan that looks like a minor edit but proposes changing the bucket&#39;s encryption. Where -generate-config-out helps is the attribute values: once each import block exists, it reads them from the provider instead of a person transcribing them across several console screens.</p><h3>Importing Multiple Resources at Once with a for_each Import Block</h3><p>Terraform 1.7 extended the import block itself with a for_each meta-argument, letting one block describe a whole batch of imports instead of writing one block per resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJ3DD4VFzfqpqxq4CVkQDA.png" /></figure><p>This narrows, without closing, the single-resource nature of import. A team still has to already know every resource ID and assemble that map before the block runs; for_each here batches known imports and doesn&#39;t discover unknown ones. That distinction between batching a known list and discovering an unknown one is the dividing line for everything that follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYktAx3LbRj_JjlUuT3y2g.png" /></figure><h3>Where Terraform Import Still Falls Short</h3><p>The import block and config generation improved the workflow. Several limitations carry over unchanged from the classic command, and the generated-config approach adds a few of its own.</p><p><strong>Import still requires knowing the resource exists.</strong> Both the classic command and the import block need a resource address and a resource ID supplied up front. Neither one searches an account for untracked resources. If a team doesn’t already know a resource is there, import can’t help them find it. That’s a discovery problem, and import was never built to solve discovery.</p><p><strong>Generated configuration isn’t guaranteed to be complete or correct.</strong> Provider support for config generation varies. Some attributes may come back blank, commented out, or set to a value that doesn’t reflect the resource’s actual configuration. The usual culprits are sensitive values, computed fields, and provider-specific settings. Treating generated output as final without review reintroduces the exact drift risk the classic workflow already carried.</p><p><strong>It’s still fundamentally single-resource, single-account.</strong> Even with import blocks, each one targets one resource. There’s no built-in mechanism to sweep an entire AWS account, let alone reconcile findings across AWS, Azure, and GCP simultaneously. A large brownfield estate, such as years of console-created infrastructure across several cloud accounts, can mean dozens or hundreds of individual import blocks. Each one needs its own resource ID lookup first.</p><p><strong>The failure mode is quiet, not loud.</strong> A mismatched import doesn’t throw an error. It produces a plan that looks like a routine update or, worse, a resource replacement, and it’s easy for that to slip through review if the reviewer doesn’t already know the resource was recently imported and isn’t yet fully verified against its generated configuration.</p><h3>Errors Worth Recognizing Before They Cause Confusion</h3><p>A handful of errors show up often enough during import work that it’s worth knowing what they actually mean rather than treating each one as a fresh mystery.</p><p><strong>“Resource already managed by Terraform.”</strong> This fires when the target address in the import command or block already has a state entry, and Terraform refuses to overwrite an existing mapping rather than silently replacing it. It usually means either the resource was already imported earlier, or the address collides with something else already declared.</p><p><strong>A plan proposing to destroy and recreate a resource immediately after import.</strong> This is almost always a configuration mismatch, not a state problem. An attribute that forces replacement, will trigger a destroy-and-recreate plan if the hand-written or generated configuration doesn’t match what is running. Examples include an AMI ID, an availability zone, and certain networking fields. Running terraform plan immediately after every import, before touching anything else, is the single best habit for catching this before it reaches an apply.</p><p><strong>Confusing import with the moved block.</strong> These solve different problems, and it’s an easy mix-up. A moved block tells Terraform that a resource already in state has been renamed or relocated in configuration, such as after a refactor. It doesn&#39;t bring anything new into state. An import block or command is for a resource that has no state entry at all yet. Reaching for moved when the actual need is import doesn&#39;t produce an error. Terraform skips a moved block whose source address isn&#39;t in state, so the plan quietly proposes creating a new resource instead, which the duplicate import was meant to prevent.</p><h3>When Manual Import Makes Sense vs. When It Doesn’t</h3><p>Import, in either form, fits a fairly narrow situation well: a small number of known resources, a team that already knows exactly what needs importing and why, and enough time to review each generated or hand-written block carefully before merging. A single orphaned security group found during an incident retro, or a handful of resources left over from a completed migration, are reasonable candidates for a direct import block.</p><p>That scoped case breaks down as the estate grows. A brownfield environment with years of undocumented, console-created infrastructure across multiple cloud accounts turns import into a resource-by-resource slog that starts with the much harder problem import doesn’t touch at all: figuring out what’s actually out there before anyone can write a single import block for it.</p><h3>How StackGuardian’s SGCode Approaches Discovery and Codification</h3><p>SGCode was built to solve the problem that terraform import leaves open, which is discovering infrastructure that no one has recorded yet. Where terraform import assumes a team already knows which resource ID needs importing, SGCode&#39;s <a href="https://docs.stackguardian.io/docs/sg-code/cloud-inventory"><strong>Cloud Inventory</strong></a> starts a step earlier: it connects directly to AWS, Azure, and GCP accounts and discovers every resource across the environment, cross-referencing what it finds against connected state backends to determine what&#39;s already managed and what isn&#39;t. That cross-cloud reach doesn&#39;t depend on running a separate command per provider or per resource, the way accumulating individual import blocks does.</p><p>Once SGCode identifies unmanaged infrastructure, its AI-powered codification step goes further than generating a resource block for a human to paste in. It generates Terraform or OpenTofu configuration for the selected resources, accounting for the relationships between them, in a Code Workbench where engineers can review and edit it. Before delivering the code, SGCode runs an internal plan and regenerates the code if that plan finds errors. Engineers can also run a test plan to check policy results before anything is pushed. The result is published as a pull request, which addresses the review-and-correct burden that generated configuration from -generate-config-out still leaves on a person’s plate: a reviewer sees a proposed PR that has already passed an internal plan check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZ_m9w6L5p5QWsI1qYEkeg.png" /></figure><p>That PR doesn’t land in a repository unguarded, either. Once the codified configuration is merged into a Workflow that has <a href="https://www.stackguardian.io/post/policy-as-code">Policy Sets</a> attached, the attached policies apply to the resulting runs the same way they apply to any other change. That holds for policies written in Tirith and for policies written in OPA. A Tirith policy scoped to the target Workflow Group, for example, can require that any encryption configuration on a newly codified S3 bucket uses KMS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6UnlkqOfZHWXeHiU_SYPQ.png" /></figure><p>This rule checks encryption resources that exist in the plan. A bucket with no encryption resource at all would not trigger it, so a real baseline pairs it with a second check that every aws_s3_bucket has a matching encryption configuration.</p><p>Brownfield resources can easily predate an organization’s current security baseline, since they were provisioned before that baseline existed. Bringing them under management through SGCode’s PR flow means they pass through the same Configuration Rules as anything else the moment they’re codified, rather than getting a quiet pass because they predate the policy.</p><p>None of this makes terraform import redundant for the case it&#39;s actually good at. A scoped, already-identified resource is often faster to bring in with a direct import block than to wait on a broader discovery pass. But for the harder version of the problem, where a team doesn&#39;t yet know what infrastructure exists, SGCode works at a different layer entirely: a real-time inventory of connected accounts with IaC coverage shown as the percentage of resources managed as code, rather than a one-off CLI operation run against a resource ID someone already had in hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFMcbKwhLbdFExnv8WqzGQ.png" /></figure><h3>Terraform Import and SGCode Together in Practice</h3><p>These aren’t competing approaches so much as tools suited to different starting points in the same underlying problem. A team that already knows about a handful of orphaned resources, whether found during an incident or left over from a decommissioned project, can reasonably reach for an import block and review the generated configuration directly. A team facing an entire pre-Terraform environment, or an acquired account with no documentation at all, needs the discovery step first, and that’s where SGCode’s Cloud Inventory does the work import was never designed to do.</p><p>A reasonable pattern in practice: use SGCode’s discovery and codification to bring a large, unknown estate under management in the first place, opening PRs as it works through the backlog, then rely on scoped terraform import blocks for the occasional one-off resource that shows up afterward, such as a new orphaned object found during a routine audit, where the team already knows exactly what it&#39;s dealing with.</p><h3>Where Should You Start With Terraform Import and SGCode</h3><p>terraform import, in both its classic and block-based forms, solves the narrow problem of writing a resource&#39;s identity into state, and adding generated configuration in Terraform 1.5 meaningfully reduced the manual transcription work that used to follow. But it was never built to answer the harder question underneath most brownfield situations: what&#39;s actually out there in the first place. That gap, not the mechanics of writing state entries, is usually the real blocker for teams sitting on years of undocumented infrastructure.</p><p>For a handful of known resources, a direct import block reviewed carefully is still the fastest path. For an estate where the real unknown is what exists at all, SGCode’s Cloud Inventory and AI-powered codification are built specifically for that discovery-first case, across every connected AWS, Azure, and GCP account, not just the one a person happens to be looking at. Explore how <a href="https://www.stackguardian.io/platform/code">SGCode</a> discovers and codifies unmanaged infrastructure, or read through<a href="https://stackguardian.io/blog/what-is-brownfield-infrastructure"> what brownfield infrastructure</a> actually looks like in practice for a deeper look at the problem.</p><h3>FAQs</h3><h3>1. What does terraform import do to my state file?</h3><p>It adds a single entry linking a resource address in your configuration to a real resource ID in the cloud. It makes no API calls that create, modify, or destroy the underlying resource, and it only changes Terraform’s own record of what it’s managing.</p><h3>2. Does terraform import write Terraform configuration automatically?</h3><p>No, the classic CLI command doesn’t write configuration. It requires a resource block to already exist and leaves writing accurate attributes to the person running the import. Import blocks paired with the -generate-config-out flag, added in Terraform 1.5, do generate a draft configuration file, but it still needs manual review before it’s trustworthy.</p><h3>3. What’s the difference between terraform import and an import block?</h3><p>The classic command is a one-off CLI operation that runs immediately and only touches state. An import block is declarative, written in .tf configuration, evaluated during a plan, and can be paired with configuration generation, making it reviewable and repeatable in a way the CLI command isn’t.</p><h3>4. Can terraform import handle bulk or unknown infrastructure discovery?</h3><p>No. Both forms of import require already knowing a resource’s type and ID before anything runs. Neither searches a cloud account for untracked resources. That’s a separate discovery problem, which tools like StackGuardian’s SGCode are built to address.</p><h3>5. Is terraform import safe to run in production?</h3><p>Yes, with a caveat. It never modifies the underlying resource, but the risk sits downstream: if the resulting configuration doesn’t exactly match what got imported, the next plan can propose an unintended change or even a destroy-and-recreate. Reviewing the plan carefully immediately after any import, generated or hand-written, is the step that actually prevents production impact.</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/terraform-import-how-it-works-and-where-it-falls-short"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef179805bc3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitOps vs DevOps: Which Approach Does Your Team Actually Need? | Blog | StackGuardian]]></title>
            <link>https://medium.com/@StackGuardian/gitops-vs-devops-which-approach-does-your-team-actually-need-blog-stackguardian-d63ed4af143b?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d63ed4af143b</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[policy-as-code]]></category>
            <category><![CDATA[cloud-governance]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 13:21:08 GMT</pubDate>
            <atom:updated>2026-11-03T13:21:08.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tejvnG9CvP8P5Pfhbxqw_Q.png" /></figure><h3>TL;DR</h3><ul><li>GitOps and DevOps aren’t competing approaches, since GitOps is a dedicated practice that implements DevOps goals for infrastructure</li><li>DevOps is a broad culture spanning planning through operations; GitOps is narrower: Git as the single source of truth with automated reconciliation.</li><li>The practical difference shows up in scope, source of truth, and versioning, not in whether a team uses one or the other exclusively.</li><li>Most teams running IaC at any real scale already practice a form of GitOps whether they’ve named it that or not.</li><li>StackGuardian implements the GitOps reconciliation loop directly in its Workflow engine, so adopting GitOps doesn’t mean stitching together a separate CI/CD pipeline, Git watcher, and drift tool.</li></ul><p>Two terms, GitOps and DevOps, get used almost interchangeably in job postings and conference talks, but they describe genuinely different things at genuinely different scopes. Consider a platform team at a mid-size fintech running its core banking APIs on Kubernetes and Terraform. They call themselves a DevOps team, and rightly so, since they plan, ship, and operate software as one coordinated group instead of two teams throwing work over a wall. But whether they’re practicing GitOps depends on something more specific: does a pull request into their infrastructure repo actually change what’s running, automatically, or does someone still SSH into a box or click through a console after the PR merges?</p><p>This post follows that same team through the rest of the piece to keep the distinction concrete: what each term actually means, how a real GitOps workflow runs step by step, where the two genuinely diverge, where they overlap, and how StackGuardian implements the GitOps reconciliation loop directly rather than requiring a separate stack of tools bolted together.</p><h3>What Is GitOps?</h3><p>GitOps is the practice of using a Git repository as the single source of truth for infrastructure, configuration, and policy. Everything that defines the desired state of a system, including resource definitions, security rules, and deployment settings, lives as declarative code in that repository, and a tool continuously compares the repository’s content against what’s actually running, reconciling any difference automatically.</p><p>Back to the fintech platform team. Their payments service needs a new security group rule to accept traffic from a partner’s IP range. Under GitOps, that change is a diff to a .tf file, aws_security_group_rule with the new CIDR block, opened as a PR. Nobody logs into the AWS console and clicks &quot;add rule.&quot; The rule doesn&#39;t exist until the PR merges, and once it does, a tool picks up the change and applies it without anyone running a command by hand.</p><p>Terraform and OpenTofu are the most common tools that implement this pattern for infrastructure. Argo CD and Flux implement the same idea for Kubernetes workloads, continuously watching a repository and applying manifest changes as they land. What this buys the team in practice: the security group change went through the same review a code change would, including a diff, a reviewer, and a merge. If that CIDR range turns out to be wrong, reverting it means restoring the previous commit, not remembering exactly what the rule looked like before.</p><h3>What Is DevOps?</h3><p>DevOps is the cultural and technical practice of bringing development and operations closer together to improve how software gets delivered, enable faster releases, reduce incidents, and tighten feedback loops between the people writing code and the people running it in production.</p><p>For the same fintech team, DevOps shows up less as a specific tool and more as how the security group change actually got proposed in the first place. The engineer who needed the new rule didn’t file a ticket and wait a week for someone else to make the change. They opened the PR themselves; a security reviewer commented that afternoon, and it merged the same day. That’s the DevOps culture piece: shared ownership and fast feedback, sitting underneath the GitOps mechanics that actually applied the change.</p><p>The lifecycle DevOps aims to improve breaks into six stages: Plan, defining requirements for a change; Code, writing it; Test, checking it for quality issues; Build, packaging it; Release, deploying it; and Operate, monitoring it once live. DevOps doesn’t prescribe a specific tool for any of these stages; it’s a set of goals and a culture of shared responsibility, not a technical specification. A team could run every one of these stages manually and still be practicing DevOps, however poorly, because unlike GitOps, DevOps requires no dedicated tooling.</p><h3>How a GitOps Workflow Actually Runs</h3><p>Following that security group rule through the full sequence:</p><ol><li>The engineer writes the change, adding the new CIDR block to the existing aws_security_group_rule resource</li><li>They push it to a branch and open a PR against the main infrastructure repository</li><li>A CI pipeline runs terraform plan, and a policy check flags anything that looks wrong; in this case, the plan is clean</li><li>The security reviewer approves the PR after confirming the IP range matches what the partner actually provided</li><li>The PR merges into main</li><li>Automated tooling detects the new commit and applies the change to the real security group</li></ol><p>Where step six happens splits into two models. <strong>Push-based</strong> reconciliation triggers immediately on the merge event; a CI/CD pipeline runs terraform apply as part of the same automation that ran the plan. <strong>Pull-based</strong> reconciliation works differently: a tool like Argo CD or Flux polls the repository independently of any merge event, notices the new commit on its own schedule, and applies it without the CI pipeline itself needing to trigger anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvjiw8ud33M-a88xFbqfpw.png" /></figure><p>The distinction matters for a scenario the fintech team hit six months earlier, before they’d set up drift detection properly. An on-call engineer manually widened a different security group during an incident, meant to narrow it back down afterward, and forgot. Push-based reconciliation alone never would have caught that; nothing merged, so nothing triggered. It sat open for three weeks until a routine security review found it. A pull-based or scheduled reconciliation model checks the live state against the repo on its own cadence, independent of whether anyone pushed anything, and would have flagged that same rule within hours instead of weeks.</p><h3>Where GitOps and DevOps Actually Diverge</h3><p>Six categories separate the two cleanly, and the fintech team’s security group change touches all six, in ways that build on each other rather than sitting as isolated facts.</p><p>Start with <strong>scope</strong>. The security group change itself stayed narrow, one resource, defined in exactly one file. But the events around it reached much further: the Slack thread where the engineer first flagged the need for the rule, the on-call rotation that eventually caught the earlier drift incident, the retro where the team decided to add scheduled reconciliation. That scope difference shapes everything else.</p><p>Because GitOps stays narrow, its <strong>processes and tools</strong> stay narrow too; in this example, Terraform and a reconciliation tool cover the entire GitOps toolchain. DevOps needed more scaffolding around that same change: a ticketing system, a Slack alert integration, an on-call scheduler, none of which have anything to do with Git-based reconciliation directly, but all of which were load-bearing for how the change actually got proposed and caught when something went wrong.</p><p>That broader toolset let the team’s <strong>automation</strong> <strong>strategy</strong> extend beyond GitOps’ own mechanics. The GitOps automation here was specifically push-based reconciliation on merge, plus the pull-based drift check added after the incident. The DevOps automation layered on top of that automated PagerDuty alerts when the on-call engineer’s manual fix created an anomaly, and automated Slack notifications when a plan showed unexpected changes, doing work no reconciliation tool by itself would have done.</p><p>Underneath all of that sits a difference in <strong>source of truth</strong>. The security group’s desired state lived in exactly one place: the Terraform file in the repo, no ambiguity. The surrounding DevOps practice didn’t work that way at all: the team’s on-call runbooks lived in a wiki, their incident postmortems in a separate tool entirely. Both were legitimate artifacts of a healthy DevOps practice, and no reconciliation loop watched either one.</p><p>That single source of truth is also why <strong>versioning</strong> worked differently for each. Every version of the security group rule is a commit, inherent to the GitOps model, no extra step required. The postmortem documenting the drift incident wasn’t versioned with anywhere near the same rigor. It’s a doc that gets edited in place, which fits DevOps in spirit but lacks GitOps’ built-in history.</p><p>All of this ties back to a difference in <strong>goal</strong>. GitOps aimed narrowly: get this one resource change applied consistently and safely. DevOps aimed at something the retro made explicit: shorten the time between “we need this rule” and “it’s live and correct,” which is exactly what justified adding scheduled drift detection afterward, a DevOps goal, implemented through GitOps tooling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEbrRQ7m-jzG9sPA5EpuQw.png" /></figure><h3>Where GitOps and DevOps Overlap</h3><p>The fintech team’s postmortem is a clean example of where these overlap in practice. The incident review was a DevOps artifact made up of a wiki page, a Slack thread, and a retro, and it concluded the fix should be a GitOps change: add scheduled drift detection so the next manually widened security group gets caught in hours instead of weeks. The retro itself wasn’t GitOps. The fix it produced was.</p><p><strong>CI/CD pipelines</strong> are how most GitOps changes actually get deployed, and CI/CD is itself a core DevOps practice; the same pipeline that ran terraform plan on the security group PR is a DevOps artifact implementing a GitOps mechanism.</p><p><strong>IaC and configuration management</strong> is the layer GitOps was built for. Terraform reconciling the security group against the repo is GitOps in action, serving the broader DevOps objective of consistent, low-incident infrastructure operations.</p><p><strong>Security and governance policy management</strong> followed the same pattern once the team matured past just fixing the immediate drift issue. Instead of relying on a human reviewer to catch every risky security group change by eye, they wrote a policy that automatically blocks any rule allowing unrestricted ingress and version-controlled it the same way they version-controlled the security group definition.</p><h3>Should You Use GitOps, or Is DevOps Enough?</h3><p>Before the drift incident, the fintech team’s setup of push-based reconciliation with no scheduled checks was arguably enough. They were small, changes were infrequent, and a security review caught the problem before it became a breach. That’s not a strategy; it’s luck, but for a genuinely small team early on, the cost of building full reconciliation rigor can outweigh what it protects against.</p><p>That calculus flips once infrastructure changes often enough, or the team grows past the point where everyone informally knows what’s currently deployed. The same team, six months after the incident, running twelve engineers and pushing infrastructure changes most days, would take on real risk by running push-only reconciliation again. Regulated environments needing an audit trail, teams past a certain size, and any environment where changes happen often enough that manual tracking becomes its own incident source, all clear the bar where GitOps rigor earns its cost quickly. This isn’t a replacement decision. Adopting stronger GitOps practices doesn’t mean abandoning DevOps culture; it means applying DevOps goals more rigorously to the infrastructure layer.</p><h3>How to Improve Your GitOps and DevOps Workflows With StackGuardian</h3><p>Most teams end up assembling GitOps from separate pieces, as the fintech team originally did: a CI/CD tool for the push half, nothing for the pull half until an incident forces the gap into view, and a policy engine bolted on afterward as a separate project. StackGuardian runs the whole loop inside one Workflow engine instead of requiring that piecemeal buildout.</p><p><strong>Workflow Triggers</strong> handle the push-based half. Configuring a Workflow’s triggers under <a href="https://docs.stackguardian.io/docs/deploy/workflows/workflow_components/source_parameters/">Source and Parameters → Configurations → VCS Triggers</a> supports a push to the tracked branch, a tag creation, a plan run on updates to all pull requests or only ones targeting the tracked branch, and an option to require plan approval before apply, covering exactly the merge-triggered reconciliation the fintech team’s security group example relied on. Triggers are available for GitHub, GitLab, and Bitbucket, not just one VCS provider.</p><p><a href="https://www.stackguardian.io/post/agentic-iac"><strong>Automated Drift Check</strong></a> is what that team was missing before the incident, and it directly fixes the gap that let a manually widened security group sit undetected for three weeks. It runs on a schedule per Workflow rather than only reacting to a push, and it queues drift runs at a lower priority than user-initiated runs so scheduled checks don’t compete with active deployments for execution capacity.</p><p><a href="https://www.stackguardian.io/post/policy-as-code-from-zero-to-enforced-guardrails-on-your-infrastructure"><strong>Policy Sets</strong></a> cover the governance improvement the same team added after their retro: the rule blocking unrestricted ingress. Written in <a href="https://docs.stackguardian.io/docs/develop/policies/policy_types/">Tirith</a>, that policy looks like this:</p><pre>{<br>  &quot;meta&quot;: {<br>    &quot;required_provider&quot;: &quot;stackguardian/terraform_plan&quot;,<br>    &quot;version&quot;: &quot;v1&quot;<br>  },<br>  &quot;evaluators&quot;: [<br>    {<br>      &quot;id&quot;: &quot;no-open-ingress-cidr&quot;,<br>      &quot;description&quot;: &quot;Block security group rules allowing 0.0.0.0/0 ingress&quot;,<br>      &quot;provider_args&quot;: {<br>        &quot;operation_type&quot;: &quot;attribute&quot;,<br>        &quot;aws_security_group_rule&quot;: &quot;aws_security_group&quot;,<br>        &quot;cidr_blocks&quot;: &quot;ingress.cidr_blocks&quot;<br>      },<br>      &quot;condition&quot;: {<br>        &quot;type&quot;: &quot;NotEquals&quot;,<br>        &quot;value&quot;: &quot;0.0.0.0/0&quot;,<br>        &quot;error_tolerance&quot;: 1<br>      }<br>    }<br>  ],<br>  &quot;eval_expression&quot;: &quot;no-open-ingress-cidr&quot;<br>}</pre><p>Scoped to the payments team’s Workflow Group, this policy automatically evaluates every security group change that runs through a Workflow in that group, regardless of whether the person opening the PR remembers to check for an open CIDR range. Each rule carries one of five statuses: Pass, Fail, Warn, Approval Required, or Unevaluated, so a genuinely risky rule can block outright while a lower-stakes tagging violation just logs a warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYw_YEtkT7RxJFvOdSG4rg.png" /></figure><p><strong>SGCode</strong> addresses a gap the security group story doesn’t even touch: <a href="https://www.stackguardian.io/post/brownfield-infrastructure">infrastructure that predates the GitOps repo entirely</a>. The fintech team’s payments service sits on a VPC that was originally clicked together in the console two years before Terraform adoption. A GitOps reconciliation model only reconciles resources that already have a corresponding definition in the repository; it says nothing about resources that were never declared. SGCode’s Cloud Inventory discovers that VPC and its dependent resources, generates the Terraform configuration, and publishes it as a pull request, bringing that two-year-old infrastructure into the same GitOps loop the security group rule already runs through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKf-CfbXXs0auUUMb9wmvA.png" /></figure><p>None of this is scoped to a single engine. Terraform, OpenTofu, CloudFormation, Ansible, Helm, and Kubectl all run as native Workflow types, so the same triggers, drift reconciliation, and policy enforcement apply whether a given Workflow is provisioning the payments VPC or deploying a Kubernetes manifest for the API layer sitting inside it.</p><h3>What a Full GitOps Loop Looks Like Inside StackGuardian</h3><p>Putting it all together as one sequence, using the fintech team’s setup after they’d fixed their gaps: an engineer opens a PR adding a new security group rule. The Workflow’s VCS trigger, configured against the team’s GitHub repository, fires on the PR, running Configuration Rules against the plan; the no-open-ingress-cidr policy evaluates the change and passes, since the new rule is properly scoped rather than open to the world. The PR gets reviewed and merged, and the merge triggers the actual apply.</p><p>That’s the push half, and it’s where most teams’ GitOps setups stop. For this team, it doesn’t. Automated Drift Check keeps running against that same Workflow on its schedule regardless of whether anything merges, so if someone widens that rule manually next quarter during another incident, it surfaces in hours rather than three weeks. Meanwhile, on a separate Workflow entirely, SGCode’s <a href="https://docs.stackguardian.io/docs/sg-code/cloud-inventory/">Cloud Inventory</a> is still working through the payments VPC’s pre-Terraform history, one resource at a time, opening PRs as it goes, each one passing through the same Configuration Rules and policy evaluation as the security group change did.</p><p>Three mechanisms inside one Workflow engine cover the same three problems that took the fintech team an incident, a retro, and a separate discovery project to solve piecemeal the first time around.</p><h3>Conclusion</h3><p>GitOps isn’t replacing DevOps, and it was never meant to. It’s DevOps applied with more rigor to one specific layer, infrastructure and its configuration, using Git as the enforcement mechanism rather than trusting the practice to happen informally. The two work together far more often than they compete, and most teams running real infrastructure at scale end up practicing some version of GitOps whether or not they’ve ever used the term.</p><p>The practical question worth asking isn’t GitOps versus DevOps. It’s whether the tooling in place actually closes the reconciliation loop, catching drift and enforcing policy continuously, or whether it only handles the push half and leaves everything else to manual vigilance until an incident forces the gap into view. That gap is where most GitOps implementations quietly fall short, and it’s the specific problem StackGuardian’s Workflow engine was built to close.</p><h3>FAQs</h3><h3>1. Is GitOps part of DevOps?</h3><p>Yes, GitOps is a subset of DevOps. It’s a specific operational model that implements DevOps principles such as automation, version control, and continuous delivery, using Git as the single source of truth for infrastructure and configuration. GitOps is narrower in scope than DevOps, which spans the entire software delivery lifecycle, so the two complement each other rather than compete.</p><h3>2. Do you still need CI/CD if you’re using GitOps?</h3><p>Yes. GitOps handles the reconciliation half, automatically applying changes once they’re merged, but something still needs to build, test, and package changes before they reach that point. CI/CD covers that earlier stage; GitOps picks up from there rather than replacing it.</p><h3>3. What’s the difference between push-based and pull-based GitOps?</h3><p>Push-based reconciliation triggers a deployment as soon as a change merges, typically through a CI/CD pipeline reacting to the commit event. Pull-based reconciliation works independently of any trigger; a tool like Argo CD or Flux polls the repository on its own schedule and applies changes it finds, catching drift introduced outside any merge event.</p><h3>4. How does StackGuardian’s drift detection fit into a GitOps workflow?</h3><p>Automated Drift Check runs on a schedule per Workflow, functioning as the pull-based half of the reconciliation loop. It catches infrastructure that’s changed outside the pipeline entirely, a manual console edit, for example, which push-based CI/CD triggered only by commits has no way to detect on its own.</p><h3>5. Can StackGuardian enforce GitOps across multiple IaC engines, not just Terraform?</h3><p>Yes. Terraform, OpenTofu, CloudFormation, Ansible, Helm, and Kubectl all run as native Workflow types, with the same triggers, drift detection, and policy enforcement applying regardless of which engine a given Workflow uses.</p><h3>6. What is the difference between GitOps and ClickOps?</h3><p>GitOps makes every infrastructure change through a commit to a Git repository, while ClickOps makes it by hand in a cloud console. A GitOps change is a reviewed commit that can be reverted, while a ClickOps change goes live with no review and no code record. That gap is how drift like the manually widened security group in this piece starts.</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/gitops-vs-devops"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d63ed4af143b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Migration: State, Policy, and What Guides Skip]]></title>
            <link>https://medium.com/@StackGuardian/terraform-cloud-migration-state-policy-and-what-guides-skip-663380b1a3aa?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/663380b1a3aa</guid>
            <category><![CDATA[terraform-cloud]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[hashicorp-terraform]]></category>
            <category><![CDATA[hashicorp]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 15:32:13 GMT</pubDate>
            <atom:updated>2026-08-14T15:32:13.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxZzTWWYAtYuYIyU2oLmEw.png" /></figure><h3>TL;DR</h3><ul><li>Terraform Cloud migration is not one problem; a team with clean Terraform coverage faces a different migration than a team carrying years of manually provisioned infrastructure.</li><li>Four things always need to be replaced, regardless of the scenario: state storage, execution infrastructure, policy enforcement, and credential management.</li><li>Most migration guides assume complete Terraform coverage. Most enterprise environments don’t have it; unmanaged resources and multi-tool sprawl are the norm, not the exception.</li><li>State import order and policy migration are where most Terraform Cloud migrations actually fail, not the platform switch itself.</li><li>StackGuardian addresses all three common scenarios through a single platform: direct state import, SGCode discovery for unmanaged resources, and a unified policy scope across Terraform, OpenTofu, CloudFormation, and other IaC tools.</li></ul><p>Two platform teams can both say they’re “migrating off Terraform Cloud” and mean entirely different projects. One team has 40 workspaces, complete Terraform coverage, and a clean state file for every resource. Another has 400 workspaces, a decade of manually provisioned AWS resources with no .tf file in sight, and three other IaC tools running alongside Terraform for different parts of the stack.</p><p>Generic migration guides tend to assume the first team. This post covers both the scenarios teams actually face and the technical patterns specific to each, and explains where a platform like StackGuardian fits, depending on which one best describes your environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sumMcB6okqn9BMB3-QOg6w.png" /></figure><h3>What Terraform Cloud Actually Bundles Together</h3><p>Terraform Cloud is not a single feature; it’s four services packaged as one product. Understanding this matters because a migration means replacing all four, not just finding a new place to run terraform apply.</p><p>The four components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIZBKXMWSHM2uZ_YklksFQ.png" /></figure><p>Migrating only the execution layer while leaving state in Terraform Cloud, or replacing state while reusing Sentinel policies that don’t port elsewhere, is not a complete migration. It’s a partial one that leaves gaps a team discovers later, usually during an incident or an audit.</p><h3>Three Migration Scenarios Teams Actually Face</h3><p>Not every team starts from the same place. The scenario determines which parts of the migration are mechanical and which parts require real engineering work before a single workspace moves.</p><h4>Clean Coverage: The Straightforward Lift</h4><p>Some teams have complete Terraform coverage. Every resource has a corresponding .tf file, every workspace maps cleanly to a piece of infrastructure, and there&#39;s no shadow layer of manually created resources sitting outside state.</p><p>In this scenario, migration is nearly mechanical. TFC Projects map to Workflow Groups, TFC Workspaces map to Workflows inside them, and TFC Variable Sets map to Reference Variables that pass values between workflows at runtime (${reference::template-group.0.outputs.cluster_name}). Sensitive workspace variables move into a Vault secret, referenced in a workflow as /secrets/vault-secret-name. The heaviest lift is exporting and reimporting state per workspace and rewriting whatever policy coverage existed in Sentinel. Most generic Terraform Cloud migration guides are written for exactly this case; it&#39;s the easiest scenario and also the least common one at any meaningful scale.</p><h4>Partial Coverage: Manually Provisioned Resources in the Mix</h4><p>Most enterprise cloud environments don’t start with Terraform. They start with console clicks, a CloudFormation template from 2019, and Terraform adopted partway through the environment’s life. An engineer provisions an RDS instance through the AWS Console during an incident. A security team modifies a security group directly to respond to a threat. None of it ends up in the state.</p><p>Migration here has two phases, not one. Unmanaged resources need to be discovered and codified before they can be governed by any platform. Terraform Cloud never saw them, and neither will whatever replaces it, unless that discovery happens first. A discovery tool connects to the live cloud account, cross-references its findings against connected state backends, and flags every resource that has no corresponding state entry. Generated Terraform or OpenTofu code for those resources gets validated through an internal plan run before it’s published as a pull request. Skipping this step means the migration replaces the platform but preserves the exact governance gap that existed before.</p><h4>Multi-IaC Sprawl: Terraform Plus Everything Else</h4><p>Platform teams running infrastructure at scale rarely use one IaC tool. Terraform handles foundational infrastructure, VPCs, networking, and IAM. CloudFormation or Pulumi manages application-layer resources. Helm deploys Kubernetes workloads. Terraform Cloud only sees the Terraform slice of this; Sentinel policies never evaluate a CloudFormation stack or a Pulumi program, and drift detection stops at the boundary of whatever Terraform manages.</p><p>This scenario turns migration into a consolidation opportunity rather than a like-for-like swap. The technical question isn’t just “where does Terraform execution move to”, it’s whether the destination platform can run CloudFormation, Helm, and Kubectl as native workflow types under the same policy scope, so a single Tirith or OPA policy can evaluate resources regardless of which tool created them, instead of each tool remaining a separate, ungoverned pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOYhiFM-8F0k7Hxnj_4i2Q.png" /></figure><h3>Where Terraform State Migrations Actually Break</h3><p>State is the asset that matters most during a migration, more than the Terraform code itself, which typically doesn’t change. Getting state migration wrong risks losing track of resources or triggering unintended changes on the first apply after cutover.</p><p>Exporting state from Terraform Cloud starts with pulling it via CLI, not downloading a file from the UI, in every case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYTQYl4TAj9g_ujONncDkA.png" /></figure><p>This writes the current state to a local JSON file. For workspaces still using TFC’s UI-driven state, the same file is available under the workspace’s <strong>States</strong> tab as the latest state version.</p><p>The failure patterns that show up most often:</p><ul><li><strong>State imported out of order</strong>: migrating a workspace whose resources depend on another workspace’s outputs, before that dependency has been migrated, breaks the reference chain</li><li><strong>Workspace-to-workflow mapping mismatches</strong>: assuming a 1:1 mapping between Terraform Cloud workspaces and the destination platform’s execution unit, when the actual structure (projects, groups, workspaces) doesn’t line up cleanly</li><li><strong>Lost variable sets</strong>: TFC variable sets applied across multiple workspaces silently, with no single view of which workspaces depended on which set, until something breaks post-migration</li><li><strong>Orphaned resources between export and import</strong>: a resource created or destroyed in the window between exporting the state and importing it into the new platform, producing a state file that no longer matches reality</li></ul><p>The sequence that avoids most of this is to lock the source workspace before exporting state, import state before reconfiguring credentials on the destination, and run a plan immediately after import. A clean plan with no unexpected changes confirms the state file matches the actual infrastructure. An unexpected diff means something changed in the gap between export and import, and it needs to be resolved before any apply runs.</p><p>For teams migrating to StackGuardian specifically, the imported .tfstate file uploads directly through the workflow&#39;s Terraform Customizations panel, with no backend block rewrite required in the Terraform code itself, as long as Use Managed Terraform State is enabled first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DljJYPtdCAn-2EAccHIx7w.png" /></figure><p>Settings → Terraform Configuration → Terraform Customizatios → Import Existing Terraform State File</p><p>If a backend needs to be configured explicitly instead of relying on the managed toggle, StackGuardian exposes an HTTP backend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsOsHTRaFmkk6mycPYAZkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWw78HR7VX9U-5qD08HQnw.png" /></figure><h3>Why Policy Migration Needs Rewriting, Not Copying</h3><p>Sentinel policies do not port to another platform. This surprises teams who assume policy is a configuration file that moves like any other artifact; it isn’t, because Sentinel’s policy language and evaluation model are specific to Terraform Cloud.</p><p>Migrating policy requires an audit first: which existing rules map cleanly to a concept on the destination platform, and which need to be rewritten because the destination platform’s policy model works differently. A rule that blocks resource deletion translates easily almost anywhere. A rule that depends on the Sentinel-specific plan structure needs to be rebuilt to work with whatever plan format the new policy engine consumes.</p><p>Policy engines also differ in language and structure. Tirith, StackGuardian’s own policy framework, uses JSON with three top-level components: meta (provider and version), evaluators (individual checks with conditions), and eval_expression (a logical combination of evaluator IDs using &amp;&amp;, ||, and !). A policy that safeguards a VPC against deletion, a common Sentinel pattern, looks like this in Tirith:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EA_cgiscJqAhthFFd2FjHA.png" /></figure><p>OPA takes a different approach entirely. Policies are written in Rego, a declarative language built for evaluating hierarchical data, and can enforce the same rule across systems beyond just the IaC platform; a Kubernetes admission controller and a Terraform pipeline can share the same Rego policy. A comparable rule blocking unencrypted S3 buckets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fo8lhijjJvC031cDK6tZSA.png" /></figure><p>Neither format is a copy-paste of Sentinel. Every policy gets rebuilt against the new engine’s schema, which is exactly why the audit step matters; rebuilding fifty policies one at a time costs far more than deciding which fifteen actually still matter.</p><p>The policy scope also needs to be redesigned, not just copied. Sentinel policies typically apply per workspace. StackGuardian scopes its policy at three levels instead: organization-wide, Workflow Groups, or Connectors (specific AWS accounts, Azure subscriptions, or GCP projects), which means the migration is an opportunity to consolidate scattered per-workspace rules into fewer, broader policies rather than recreating the same fragmentation. Rather than rewriting every policy from scratch, the Policy Marketplace has 250+ pre-built templates covering CIS benchmarks, PCI DSS, tagging, and encryption enforcement that can be subscribed to directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3RAhQrgATE6lVJqR1889A.png" /></figure><h3>How StackGuardian Addresses Each Migration Scenario</h3><p>A platform’s fit depends on which scenario above matches an environment. Here’s how StackGuardian’s architecture maps to each one, with the specific mechanics involved.</p><h4>Clean Coverage: Direct State Import</h4><p>Migration starts with connecting a cloud provider and VCS as Connectors, set up once at the org level and attached per workflow rather than configured per workspace, the way TFC does it. The workflow itself follows a wizard that covers Source and Parameters (the Git repo and working directory), Terraform Configuration, Deployment Environment, and Terraform Version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7pvAMxTeNp1xzMSaxf56A.png" /></figure><p>In Terraform Configuration, enabling Use Managed Terraform State under Terraform Customizations enables a centralized backend with locking, versioning, and encryption, with no S3 bucket or DynamoDB table required. With that enabled, the exported .tfstate file uploads directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sI3Z0aRanzjy_YHyfsP9A.png" /></figure><p>Triggering a plan immediately after upload runs drift detection against the imported state. A clean plan confirms the migration is safe; an unexpected diff means something needs investigating before any apply runs.</p><h4>Partial Coverage: SGCode Before Any Workflow Exists</h4><p>For environments with unmanaged infrastructure, migration starts earlier, before any Workflow is created. SGCode connects to AWS, Azure, and GCP accounts through its Cloud Inventory, discovers every resource across the environment, and cross-references its findings against connected state backends under SGCode → State Backends.</p><p>Resources with no corresponding state entry get flagged as candidates for codification. Selecting them triggers AI-assisted generation of Terraform or OpenTofu configuration, which resolves inter-resource dependencies and validates the output through an internal plan run before publishing the result as a pull request to a connected Git repository. Only after that PR merges does the resource become eligible for a governed Workflow; codification is a prerequisite step, not something that happens in parallel with migration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmaqQxv_eMGWBDDcpVTtXQ.png" /></figure><h4>Multi-IaC Sprawl: One Platform, Multiple Workflow Types</h4><p>StackGuardian supports Terraform, OpenTofu, CloudFormation, Ansible, Helm, Kubectl, and Terragrunt as native workflow types, along with custom runtime containers for anything not natively supported. Each tool has its own Workflow, but Workflow Groups and the policies scoped to them apply the same way regardless of which IaC tool a given Workflow runs on.</p><p>A Tirith or OPA policy scoped to a Workflow Group evaluates every Workflow inside it, whether that Workflow runs terraform plan or a Helm chart deployment. This closes the exact gap that Sentinel left open: Sentinel only ever evaluated Terraform plans, so a CloudFormation stack or a Helm release ran with zero policy coverage. Consolidating under one platform means a single policy definition, not five disconnected pipelines each needing its own governance layer bolted on separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emnp5sh-GfUSAimjOg9k7A.png" /></figure><h4>Running Terraform CLI Against the New Backend</h4><p>Teams used to running terraform plan locally rather than through a UI wizard aren&#39;t locked out of that workflow after migration. Enabling Use Managed Terraform State and adding a cloud block to the Terraform configuration points the CLI at StackGuardian instead of Terraform Cloud:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXHcRGsu-IXM9PSoXISlKA.png" /></figure><p>terraform init and terraform plan, then run remotely against StackGuardian the same way they did against TFC. One difference matters: terraform apply must be triggered either from the platform or via a VCS trigger, not directly from the CLI. State locking works the same way as in Terraform Cloud: the CLI acquires a lock, StackGuardian queues any conflicting runs, and the lock is released automatically once the operation completes.</p><h3>A Migration Checklist That Holds Across All Three Scenarios</h3><p>Regardless of which scenario describes an environment, the same operational discipline applies. This checklist stays scenario-agnostic on purpose; the specifics change, but the sequence doesn’t.</p><ul><li>Inventory everything before touching anything: workspaces, variable sets, policies, and (for partial coverage) unmanaged resources</li><li>Lock the source workspace before exporting state to prevent conflicting runs during the export window</li><li>Migrate the state before reconfiguring credentials on the destination platform</li><li>Migrate and rewrite policy before cutover, not after. Governance gaps are easy to miss once a workflow is live</li><li>Run a plan immediately after every state import and treat any unexpected diff as a blocker, not a warning</li><li>Cut over one workspace group at a time, never the entire environment simultaneously</li></ul><p>A staged migration following this sequence limits the blast radius. If something breaks during the migration of one group, the rest of the environment stays untouched, and the issue stays contained.</p><h3>Migration Scope Depends on Where a Team Is Starting From</h3><p>The technical work behind a Terraform Cloud migration changes shape entirely depending on starting conditions. A team with clean coverage is doing state export and credential reconfiguration. A team with a decade of manually provisioned infrastructure is doing discovery and codification first, then migration. A team running multiple IaC tools is deciding whether the migration is a chance to consolidate governance or just a lateral move to a new execution layer.</p><p>What stays constant across all three is the discipline: state moves before credentials, policy gets rewritten before cutover, and staged rollout beats a single big-bang switch every time. Identifying which scenario actually describes the environment before writing a migration plan is what separates a migration that goes smoothly from one that surfaces problems six months later during an audit.</p><h3>FAQs</h3><h4>1. How do I migrate Terraform state without losing history or triggering unintended changes?</h4><p>Export the state using terraform state pull, lock the source workspace to prevent conflicting runs during the export window, and import the state file into the destination before reconfiguring any credentials. Run a plan immediately after import; a clean plan with no unexpected changes confirms the imported state matches actual infrastructure.</p><h4>2. What happens to unmanaged cloud resources that were never in Terraform state?</h4><p>They need to be discovered and codified before any platform can govern them. Terraform Cloud never saw them, and a new platform won’t either unless discovery happens first. Tools like SGCode connect to cloud accounts, identify resources without corresponding IaC, and generate Terraform or OpenTofu configurations for them as a prerequisite for migration.</p><h4>3. Can I migrate a multi-IaC environment running Terraform alongside CloudFormation or Pulumi to one platform?</h4><p>Yes, if the destination platform natively supports multiple IaC tool types, not just Terraform. StackGuardian runs Terraform, OpenTofu, CloudFormation, Ansible, Helm, and Kubectl as native workflow types under a single policy and execution layer, closing the gap left by Sentinel-only governance that left non-Terraform tools ungoverned.</p><h4>4. Do Sentinel or OPA policies transfer directly to a new platform?</h4><p>Sentinel policies do not transfer to other platforms; they must be audited and rewritten for the destination platform’s policy engine. OPA policies written in Rego can often be reused directly if the destination platform supports sourcing Rego from a Git repository, since the policy language itself doesn’t change.</p><h4>5. How long does a Terraform Cloud migration typically take for an enterprise environment?</h4><p>It depends heavily on which scenario describes the environment. Clean coverage with complete Terraform state typically migrates in hours per workspace. Partial coverage with significant unmanaged infrastructure adds a discovery and codification phase that can take considerably longer, since this work must occur before any workspace migration begins.‍</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/terraform-cloud-migration"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=663380b1a3aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Policy as Code: Zero to Enforced Guardrails]]></title>
            <link>https://medium.com/@StackGuardian/policy-as-code-zero-to-enforced-guardrails-9225aa489ee0?source=rss-0cb33cc953f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9225aa489ee0</guid>
            <category><![CDATA[open-policy-agent]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[tirith]]></category>
            <category><![CDATA[policy-as-code]]></category>
            <category><![CDATA[cloud-governance]]></category>
            <dc:creator><![CDATA[StackGuardian]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 09:00:51 GMT</pubDate>
            <atom:updated>2026-08-07T09:00:51.054Z</atom:updated>
            <content:encoded><![CDATA[<p>Policy as Code turns governance into version-controlled, auto-enforced rules. See how Tirith and OPA block bad deployments before they ship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ncyHx1JPMKNJUiKQQXICw.png" /></figure><h3>TLDR</h3><ul><li>Policy as Code moves infrastructure governance out of wikis and Slack threads into version-controlled, automatically enforced rules that run on every pipeline execution, before anything touches production.</li><li>The four pillars that make it work are definition, enforcement, testing, and drift monitoring. Skip any one, and the system has gaps that only show up during an audit or an incident.</li><li>StackGuardian’s Tirith framework lets you write policies in JSON against Terraform plans, InfraCost data, workflow configs, and Kubernetes manifests, with a final_expression that combines evaluators using &amp;&amp;, ||, and ! logic.</li><li>For policies that need to run across multiple systems beyond StackGuardian, Kubernetes admission control, API gateways, CI runners, and OPA with Rego give you that portability, and StackGuardian supports sourcing Rego policies directly from a Git repo.</li><li>Enforcement scope (org-wide, workflow group, or connector-level), rule actions (pass, warn, approval required, fail), and automatic drift detection mean policy coverage is continuous, not just a gate at deploy time.</li></ul><p>Infrastructure governance sounds simple until you’re managing hundreds of cloud resources across multiple teams and providers. The usual approach, a senior engineer reviewing Terraform plans, a quarterly compliance checklist, and a Slack message as the approval trail, breaks down fast. Rules live in wikis, tribal knowledge, and one person’s head. When that person becomes the bottleneck, it’s not a process problem. It’s an architecture problem.</p><p>Policy as Code fixes this by turning governance rules into structured, version-controlled code that runs automatically on every pipeline execution, before anything touches production. This post covers what Policy as Code is, how it works under the hood, and how StackGuardian implements it through its Tirith policy framework and Open Policy Agent support, with real policy JSON pulled straight from the docs.</p><h3>What is Policy as Code</h3><p>Policy as Code treats governance rules the same way software teams treat application code: written in a structured format, stored in version control, reviewed through pull requests, tested before deployment, and automatically executed by the system.</p><p>A policy might say “no EC2 instance can be deployed without an Environment and Owner tag,” or “no workflow targeting production can run without pre-approval,” or “monthly EC2 spend must stay under $100.” Without codification, those rules depend on someone checking. With Policy as Code, the system checks every time, with no manual step in the path.</p><p>The contrast with manual governance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Y9YKvnd-q9tfXhk-pnHKA.png" /><figcaption>Policy as Code is especially useful in multi-cloud environments. AWS, Azure, and GCP each have their own native governance tools, AWS Config, Azure Policy, and GCP Organization Policies, that don’t interoperate. Policy as Code creates a single enforcement layer that sits above provider-specific tooling and applies the same rules regardless of which cloud is being provisioned.</figcaption></figure><h3>What Every Policy-as-Code System Requires</h3><p>Before getting into the tools, it helps to understand the four components that any working Policy-as-Code system requires. Miss one, and the enforcement model has holes.</p><h4>1. Policy Definition</h4><p>Rules are written in a structured format, JSON, YAML, or a domain-specific language like Rego, and stored in version control. This is where precision matters. A policy that says “enforce encryption” is not enforceable as written. A policy that says “check that aws_s3_bucket has server_side_encryption_configuration set, and its rule contains AES256 or aws:kms” is. Definitions should be specific enough to be evaluated unambiguously.</p><h4>2. Enforcement</h4><p>A policy definition does nothing on its own until something executes it against real inputs. Enforcement is the mechanism that evaluates planned infrastructure changes or running configurations against those definitions and takes action when something doesn’t comply, blocking the deployment, warning the team, or routing to an approval gate.</p><h4>3. Testing</h4><p>Policies need to be tested before they reach production environments. A policy that’s too broad blocks legitimate deployments. One that’s too narrow misses the violations it was written to catch. Testing against representative Terraform plans in a non-production context catches both classes of problems before they create friction.</p><h4>4. Monitoring and Drift Detection</h4><p>Environments change after deployment. A resource that was compliant when provisioned may be manually reconfigured, have a dependency updated, or drift from its declared state in any number of ways. Continuous monitoring detects these changes and maintains the audit trail compliance teams need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxA-K1miU54WNiysiuYkew.png" /></figure><h3>What Policy as Code Looks Like in Practice</h3><p>Before getting into how StackGuardian implements each of these components, it helps to see what the enforcement loop actually looks like when it’s working.</p><p>Take a simple example: your organization has a rule that all AWS EC2 instances must have an Environment and Owner tag. Without Policy as Code, that rule lives in a Confluence doc. Someone forgets, an untagged instance gets deployed, and it shows up three months later in a cost audit with no owner.</p><p>With Policy as Code, that rule is a file in your repo. Every time a Terraform plan is generated, the policy engine evaluates the plan against the rule before terraform apply runs. If the instance is missing the tag, the pipeline stops. The engineer sees exactly which resource violated which rule and fixes it before anything hits production.</p><p>The same model applies to more complex rules, requiring approval before any workflow targets a production environment, blocking EC2 instance types above a certain cost tier in dev, or preventing security groups from allowing inbound SSH from 0.0.0.0/0. Each of these is a policy definition evaluated automatically at the right point in the pipeline, with a configured action determining what happens on violation: block outright, warn and continue, or pause for a human approver.</p><p>This is the enforcement loop: write the rule once, attach it to a scope, and it runs on every relevant deployment without anyone having to remember to check. The rest of this post covers how StackGuardian implements this loop through its policy model, its two enforcement engines, and the tooling that makes it practical for teams at different levels of policy maturity.</p><h3>How StackGuardian Structures Policy Enforcement</h3><p>StackGuardian treats policies as a set of rules that act as guardrails across workflows and cloud infrastructure. Policies evaluate planned changes before they run and can block, warn, or gate them for approval, depending on how a rule is configured.</p><p>Every policy in StackGuardian has two parts: a <strong>Meta</strong> tab that controls where it applies (scope), and a <strong>Rules</strong> tab that defines what gets evaluated and what happens on pass or error.</p><h4>Scope</h4><p>Scope determines which resources a policy covers. Three levels are available:</p><ul><li><strong>Organization-wide</strong>: the policy applies to all workflows and stacks across the organization</li><li><strong>Workflow Groups</strong>: applied only to specific operational areas you select</li><li><strong>Connectors</strong>: scoped to specific AWS accounts, Azure subscriptions, or GCP projects</li></ul><p>StackGuardian automatically determines the policy type from its content and enforces it on workflows or infrastructure configurations accordingly. A policy that contains a ${curr_workflow} reference in an evaluator applies only to workflows. A policy using ${curr_stack} applies only to stacks. Policies without either reference apply to both.</p><h4>Rule Actions</h4><p>Each rule has two configurable outcomes: <strong>Action when policy passes</strong> and <strong>Action when policy errors</strong>. The available actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-XbCHPahdWgp5gQjzQMPw.png" /></figure><p>For rules requiring approval, you configure the number of approvers from a pre-defined list, ranging from one to all approvers. This creates an audit trail for every manual exception.</p><h3>The Two Policy Engines: Tirith and OPA</h3><p>StackGuardian supports two policy engines. Which one to use depends on how complex your policies are and how much your team wants to write.</p><h4>Tirith: StackGuardian’s JSON-Based Policy Framework</h4><p>Tirith is StackGuardian’s own policy framework, built for IaC and workflow compliance. It scans Terraform plans, CloudFormation, Kubernetes manifests, and workflow JSON against policies you define in JSON. The design goal is readability: a Tirith policy should be interpretable by someone who didn’t write it, without requiring knowledge of a specialized policy language.</p><p>Every Tirith policy has three top-level components:</p><ul><li>meta: specifies the provider (stackguardian/terraform_plan, stackguardian/infracost, stackguardian/sg_workflow, stackguardian/kubernetes, stackguardian/json) and the schema version</li><li>evaluators: an array of individual checks, each with an id, provider_args pointing at the specific attribute or action being checked, and a condition defining the evaluation logic</li><li>eval_expression: a logical expression combining evaluator IDs using &amp;&amp; (AND), || (OR), and ! (NOT)</li></ul><h4>Tirith Provider: stackguardian/terraform_plan</h4><p>The Terraform plan provider checks attributes, actions, counts, and dependencies in a Terraform plan. The operation_type field controls what kind of check runs:</p><ul><li>attribute: check the value of a specific resource attribute</li><li>action: check whether a resource is being created, deleted, or unchanged (no-op)</li><li>count: check the number of resources of a given type</li><li>direct_references: verify that one resource is referenced by another (e.g., a bucket referenced by a lifecycle policy)</li><li>direct_dependencies: check for dependency relationships between resources</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fP5bXCzGu2zK7R_q_hW6GA.png" /></figure><p>Policy that prevents an aws_vpc from being deleted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF80JTSmGVEhFZcW-DUMEQ.png" /></figure><ul><li>0: all values (Resource Type, Resource Attribute, Condition value) must be present and correct, otherwise the policy fails</li><li>1: If the specified Resource Type is not present in the deployment, the policy is skipped rather than failed</li><li>2: If the Resource Type or Resource Attribute is not configured, the policy is skipped</li></ul><p>The error_tolerance field controls how Tirith handles missing resources during evaluation. Three values are supported:</p><p>Available condition types: Equals, NotEquals, GreaterThan, GreaterThanEqualTo, LessThan, LessThanEqualTo, ContainedIn, IsNotEmpty, RegexMatch.</p><h4>Tirith Provider: stackguardian/infracost</h4><p>The InfraCost provider checks cloud spend at plan time, before any resources are created. The operation_type can be total_monthly_cost or total_hourly_cost. You specify resource_type as a list of resource types to target, or use the ALL ()* operator for a policy that applies across all resources.</p><p>Policy that limits EC2 monthly spend to under $100:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkX0NovaZMMnhLFRD8R9tA.png" /></figure><h4>Tirith Provider: stackguardian/sg_workflow</h4><p>The SG Workflow provider validates JSON-based workflow configurations. A common use case is enforcing that pre-apply approvals are enabled on production workflows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8qQenVQzdzZxexqf9pc8Q.png" /></figure><p>This policy triggers an error on any workflow where approvalPreApply isn&#39;t set to true. What happens next depends on the configured error action for the rule.</p><h4>Tirith Provider: stackguardian/kubernetes</h4><p>The Kubernetes provider checks resource attributes on Kubernetes manifests. The operation_type is an attribute; kind specifies the resource kind (e.g., Pod); and attribute uses dot notation with wildcard support. For example, spec.containers.*.livenessProbe checks that all containers in a Pod spec have a liveness probe defined.</p><h4>Combining Evaluators</h4><p>The eval_expression field is where Tirith policies get compositional. Multiple evaluators can be combined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPbcEIYNMu677MEp7MAW4w.png" /></figure><p>This lets you express policies like “check A AND check B must pass, OR check C must not trigger”, useful for conditional logic like “require tagging on all resources except those in the sandbox workspace.”</p><h4>Running Tirith Locally</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p33yDCvtqRHnX8hoLW0NYg.png" /></figure><p>The --json flag outputs results in machine-readable JSON, useful when piping into other tools. The --verbose flag shows detailed per-evaluator logs.</p><h4>OPA: For Policies That Need More Expressiveness</h4><p>Open Policy Agent is a CNCF-graduated, open-source general-purpose policy engine. Policies are written in Rego, a declarative language built specifically for expressing rules over complex hierarchical data. OPA decouples decision-making from enforcement: your system queries OPA with structured JSON input, and OPA returns a decision.</p><p>OPA runs across Kubernetes admission control, CI/CD pipelines, API gateways, and microservices. It’s the right choice when your policies need to cross system boundaries, enforcing the same rule in StackGuardian workflows and in a Kubernetes admission controller, for example.</p><ol><li>Uncheck <strong>Marketplace Policy Template</strong></li><li>Set <strong>Source Config Kind</strong> to Open Policy Agent</li><li>Select the VCS where your Rego policies are stored (github.com or git (other))</li><li>Provide the repository URL, reference branch, and working directory</li><li>For private repos, authenticate via a secret in StackGuardian Vault (/secrets/vault-secret-name) or via /integrations/github_com)</li><li>Set the <strong>OPA Deciding Query</strong>, the Rego rule returning the final boolean, formatted as &lt;opa-package-path&gt;.&lt;rule-name-returning-boolean&gt;</li></ol><p>In StackGuardian, OPA policies are sourced from a version-controlled repository. To configure an OPA policy inside a rule:</p><p>Optionally, pass JSON through the code editor as policy data to template Rego policies, reusing the same logic across multiple policy definitions.</p><p>A minimal Rego policy that blocks S3 buckets without encryption:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziErJiNQxvy7HMPAHZ6Crg.png" /></figure><p>The OPA deciding query for this would be terraform/s3/deny.</p><h4>Tirith vs OPA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdRvBkWHWhqZyujSwimJxw.png" /><figcaption>If your policies cover Terraform resource attributes, costs, workflow approvals, and Kubernetes manifests and run inside StackGuardian, Tirith is the right choice. If you need the same policy logic to run across StackGuardian and another system (such as a Kubernetes cluster, an API gateway, or a CI runner), OPA provides that portability.</figcaption></figure><h3>NoCode Policy Builder: For Teams That Don’t Want to Write JSON</h3><p>For teams that want policy enforcement without writing Tirith JSON directly, StackGuardian’s NoCode Policy Builder generates the equivalent policy through a UI.</p><p>To access it:</p><ol><li>Navigate to <strong>Orchestrator → Policy Sets → Create Policy (or via Develop → Policy Sets)</strong></li><li>In the Rules tab, click <strong>Add new Policy Rule</strong></li><li>Uncheck <strong>Marketplace Policy Template</strong></li><li>Set <strong>Source Config Kind</strong> to Tirith (StackGuardian Policy Framework) and sourceConfigDestKind to inline</li><li>Select the <strong>No Code</strong> option</li><li>Choose a provider, click <strong>Add Evaluator</strong>, and assign a unique Evaluator ID</li><li>Configure the operation type, condition type, and condition value</li><li>Combine evaluators in the <strong>Final Expression</strong> field</li></ol><p>The NoCode builder produces the same JSON that Tirith would evaluate; it’s a UI layer on top of the same engine, not a separate system. Teams can start with NoCode and inspect the generated JSON to learn the schema.</p><h3>The Policy Marketplace: 200+ Pre-Built Policies</h3><p>Writing policies from scratch isn’t always necessary. StackGuardian’s Policy Marketplace has over 200 pre-built policies covering AWS, Azure, and GCP best practices, CIS benchmarks, tagging requirements, encryption enforcement, SSH access restrictions, and more.</p><p>To use a marketplace policy:</p><ol><li>Navigate to <strong>Develop → Policy Sets → Create Policy</strong></li><li>In the Rules tab, name the rule and select <strong>Marketplace Policy Template</strong></li><li>Search for the template (e.g., /stackguardian/aws-best-practices-all) and select the latest version</li><li>Set <strong>Action on pass</strong> to PASS and <strong>Action on fail</strong> to WARN (or FAIL if you want hard blocking)</li><li>Save, then set the scope under the Meta tab</li></ol><p>Marketplace policies can be customized after subscription, and organizations can publish their own templates to share standardized policies across teams.</p><h3>What the Enforcement Flow Looks Like End to End</h3><p>Putting this together, here’s what happens when a developer triggers a workflow in StackGuardian:</p><ol><li>The workflow is triggered (via Self-Service, GitOps, API, SDK, Terraform provider)</li><li>StackGuardian evaluates all policies scoped to that workflow, workflow group, or connector.</li><li>Configuration Rules are evaluated first at workflow creation, update, or runtime.</li></ol><p>If a Configuration Rule fails, the run is blocked immediately. If it passes or warns, Runtime Rules then evaluate during execution. If it requires approval, the run waits until approval is granted</p><p>4. Runtime Rules evaluate during actual workflow execution</p><p>5. Each rule returns one of five statuses: Pass, Fail, Warn, Approval Required, or Unevaluated</p><p>6. Based on configured actions: the workflow proceeds, a warning is logged, an approval request is routed to a named approver, or the workflow is blocked</p><p>7. Every evaluation is logged with the full result, making the audit trail automatic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1CszJpZ0U-1dOHU80om7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZco2Isd2J6o5cCGN_eJRQ.png" /></figure><p>Drift detection runs continuously; resources that were compliant at deployment are flagged when they diverge from the declared state, without waiting for the next deployment to catch them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9y1l04HymTAF6bIUeqLqQ.png" /></figure><h3>Why Centralized Policy Enforcement Matters</h3><p>Running policies as standalone scripts or one-off checks doesn’t solve the underlying problem. Without a platform enforcing them, policies can be skipped, misconfigured, or simply not applied to new workflows that spin up after the policy was written.</p><p>StackGuardian’s policy engine attaches to scopes, organizations, workflow groups, or connectors, so any new workflow that falls within scope automatically inherits enforcement. RBAC controls who can create, modify, or override policies. Audit logs capture every evaluation. And drift detection closes the loop for runtime compliance, not just deployment-time compliance.</p><p>The goal isn’t to slow teams down. It’s to make non-compliant deployments structurally harder than compliant ones, without requiring someone to be in the loop for every change.</p><h3>Conclusion: Governance That Runs With Your Pipeline</h3><p>Policy as Code moves governance from a manual checkpoint into a structural property of your pipeline, version-controlled, automatically enforced, and consistent regardless of team size or cloud provider. The four pillars, StackGuardian’s Tirith engine and OPA support, scope inheritance, and drift detection give you everything needed to build a governance model that grows with your infrastructure rather than falling behind it.</p><p>A good place to start is to scope one policy to a single workflow group, set the action to Warning, and see what it catches, then expand from there. The Tirith CLI lets you test policies locally against real plan outputs before attaching them to any workflow, so you can validate behavior without touching a live environment. If you want to see how this works end-to-end,<a href="https://stackguardian.io/"> StackGuardian’s policy engine</a> is worth exploring.</p><h3>FAQ</h3><h4>1. What is the difference between Tirith and OPA for Policy as Code in StackGuardian?</h4><p>Tirith is StackGuardian’s own JSON-based policy framework built specifically for IaC compliance. It evaluates Terraform plans, InfraCost data, Kubernetes manifests, and workflow JSON using a declarative evaluator model with meta, evaluators, and eval_expression. OPA uses Rego, a general-purpose policy language, and can enforce the same policy logic across StackGuardian, Kubernetes admission controllers, API gateways, and CI runners. Use Tirith when your policies live entirely within StackGuardian; use OPA when you need cross-system portability.</p><h4>2. How does Policy as Code enforcement work in a Terraform CI/CD pipeline?</h4><p>When a workflow is triggered in StackGuardian, via GitOps push, API, SDK, or Terraform provider, the platform evaluates all scoped policies before the Terraform apply runs. Configuration Rules fire first at create/update/run time, followed by Runtime Rules during execution. Each rule returns one of five statuses: Pass, Fail, Warn, Approval Required, or Unevaluated. Violations can block the run outright, trigger a warning, or route to a named approver, all of which are logged automatically for audit.</p><h4>3. What is infrastructure drift, and how do you detect it in multi-cloud environments?</h4><p>Infrastructure drift occurs when the actual state of cloud resources diverges from their declared IaC configuration, typically due to manual console changes or dependency updates. In multi-cloud environments, drift is harder to catch because AWS, Azure, and GCP each track configuration state independently. StackGuardian’s drift detection runs continuously against deployed resources, flagging divergence from Terraform state without waiting for the next pipeline run. Detected drift surfaces under the workflow’s Overview tab alongside compliance check results.</p><h4>4. What is the error_tolerance field in a Tirith policy, and when should you set it to 1 or 2?</h4><p>error_tolerance controls how Tirith handles missing resources during evaluation. Set it to 0, and all values, Resource Type, Resource Attribute, and Condition value, must be present and correct, or the policy fails. Set it to 1, and Tirith skips the evaluator if the specified Resource Type isn&#39;t present in the deployment, rather than failing the deployment. Set it to 2, and the evaluator is skipped if either the Resource Type or Resource Attribute isn&#39;t configured. Use 1 or 2 when writing broad policies that should apply to multiple deployment types, where not every resource will always exist.</p><h4>5. What is the difference between a Workflow Policy and a Stack Policy in StackGuardian?</h4><p>A Workflow Policy applies to workflow-level configurations and runs; you scope it by including a ${curr_workflow} reference in an evaluator. A Stack Policy applies to stacks, using ${curr_stack}. Policies without either reference apply to both. The practical difference matters when you need to enforce approval gates or compliance checks at different layers. A workflow policy can block a run before it executes, while a stack policy governs the stack configuration and the resources provisioned within it.</p><p><em>Originally published at </em><a href="https://www.stackguardian.io/post/policy-as-code"><em>https://www.stackguardian.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9225aa489ee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>