Blog

GitHub Actions Workflows for Terraform at Scale: Automated Generation

24.11.2026
Reading time: 8 mins.
Last Updated: 24.11.2026

Table of Contents

As Terraform repositories grow, GitHub Actions workflows for Terraform can become repetitive very quickly.

A repository may start with a single environment and one workflow. Later, dev, stg, and prod are added, together with reusable Terraform modules for networking, databases, monitoring, and other infrastructure.

The workflows for those environments are usually very similar. In most cases, only a few things change:

  • the Terraform working directory
  • the paths that should trigger the workflow
  • whether Terraform should run a plan or an apply

Maintaining a separate workflow manually for every environment works, but it also means maintaining the same logic in several places.

Eventually, one workflow gets updated while another does not, a newly added module is missing from a path filter, or a new environment is created without the corresponding CI configuration.

To avoid that, Terraform GitHub Actions workflows can be generated automatically.

The approach described here uses a Python generator to discover Terraform environments and their dependencies, create the required GitHub Actions workflows, and keep them updated automatically through a Git pre-commit hook.

github actions

For this example, Terraform environments are stored under:

terraform/envs/dev
terraform/envs/stg
terraform/envs/prod

Reusable modules are kept separately, for example:

terraform/modules/database
terraform/modules/networking
terraform/modules/monitoring

There is also a reusable GitHub Actions workflow responsible for the actual Terraform execution.

The basic flow is:

Terraform environments -> workflow generator -> generated GitHub Actions workflows -> reusable Terraform workflow

The generated workflows decide when Terraform should run and which environment should be targeted. The reusable workflow contains the common execution logic.

This keeps environment-specific configuration small while avoiding duplicated Terraform setup across multiple workflow files.

There is no need to maintain another configuration file containing the list of environments.

The generator can simply inspect terraform/envs and treat every environment directory as a deployment target.

A simplified version of the environment discovery can look like this:

from pathlib import Path



ENVS_DIR = Path("terraform/envs")

def discover_environments():

    return [

        path.name

        for path in ENVS_DIR.iterdir()

        if path.is_dir() and path.name != "template"

    ]

For example:

dev -> generate dev.yml
stg -> generate stg.yml
prod -> generate prod.yml

A directory such as template can be excluded because it is not a real deployment environment.

With this approach, adding a new environment does not require updating a separate CI configuration.

If a new directory such as:

terraform/envs/test

is added, the generator can discover it automatically and create the corresponding workflow.

The repository structure becomes the source of truth for Terraform environments.

Knowing which environments exist is only part of the problem.

The generator also needs to know what should trigger each GitHub Actions workflow.

Running every Terraform workflow whenever any Terraform file changes would work, but it would also create many unnecessary CI runs.

For example, assume that prod uses:

database
networking
monitoring

while dev only uses:

database
networking

A change to the monitoring module should trigger the production workflow, but it does not necessarily need to trigger the development workflow.

The generator can inspect the Terraform code in each environment and determine which reusable modules are referenced.

One simple way to do that is to search the environment for module references:

import subprocess



def module_is_used(environment_path, module_name):

    result = subprocess.run(

        [

            "git",

            "grep",

            "-q",

            module_name,

            "--",

            str(environment_path),

        ],

        check=False,

    )

    return result.returncode == 0

In this example, git grep is used to check whether a module is referenced by a particular environment.

The dependency discovery itself can be implemented in different ways, but the goal is the same: determine which shared Terraform code can affect each environment.

The dependency relationship could therefore look like this:

prod -> database, networking, monitoring

dev -> database, networking

stg -> database, networking, monitoring

Those dependencies are then converted into GitHub Actions path filters.

For prod, the generated paths could look like:

paths:

– terraform/envs/prod/\*\*

– terraform/modules/database/\*\*

– terraform/modules/networking/\*\*

– terraform/modules/monitoring/\*\*

For dev:

paths:

– terraform/envs/dev/\*\*

– terraform/modules/database/\*\*

– terraform/modules/networking/\*\*

This makes the workflows more selective without requiring someone to manually maintain a list of dependencies for every Terraform environment.

Once the environment and its dependencies are known, the generator can create the GitHub Actions workflow.

A simplified Python function for building the workflow could look like this:

def build_workflow(environment, paths):

    return {

        "name": f"Infrastructure - {environment}",

        "on": {

            "pull_request": {

                "paths": paths,

            },

            "push": {

                "branches": ["main"],

                "paths": paths,

            },

        },

        "jobs": {

            "plan": {

                "uses": "./.github/workflows/terraform-run.yml",

                "with": {

                    "environment": environment,

                    "command": "plan",

                },

            },

            "apply": {

                "if": "github.event_name == 'push'",

                "uses": "./.github/workflows/terraform-run.yml",

                "with": {

                    "environment": environment,

                    "command": "apply",

                },

            },

        },

    }

The resulting Python dictionary can then be serialized to YAML and written to the corresponding file under .github/workflows.

For example:

from pathlib import Path

from ruamel.yaml import YAML



yaml = YAML()





def write_workflow(environment, workflow):

    output = Path(".github/workflows") / f"{environment}.yml"



    with output.open("w") as workflow_file:

        yaml.dump(workflow, workflow_file)

A simplified generated GitHub Actions workflow could look like this:

name: Infrastructure - prod



on:

  pull_request:

    paths:

      - terraform/envs/prod/\*\*

      - terraform/modules/database/\*\*

      - terraform/modules/networking/\*\*

      - terraform/modules/monitoring/\*\*



  push:

    branches:

      - main

    paths:

      - terraform/envs/prod/\*\*

      - terraform/modules/database/\*\*

      - terraform/modules/networking/\*\*

      - terraform/modules/monitoring/\*\*



jobs:

  plan:

    if: github.event_name == 'pull_request'

    uses: ./.github/workflows/terraform-run.yml

    with:

      environment: prod

      command: plan



  apply:

    if: github.event_name == 'push'

    uses: ./.github/workflows/terraform-run.yml

    with:

      environment: prod

      command: apply

The generated workflow does not need to contain all the Terraform commands.

Its purpose is mainly to define:

  • which files are relevant to the environment
  • which GitHub event should start the job
  • which environment should be used
  • whether Terraform should run plan or apply

The actual Terraform execution is delegated to a reusable workflow.

Most environments use the same Terraform steps:

Authentication -> terraform init -> validation -> plan/apply -> publish result

Repeating all of this in dev.yml, stg.yml, prod.yml, and every future environment would bring us back to the original problem.

Instead, the environment workflows call the same reusable workflow:

uses: ./.github/workflows/terraform-run.yml

and provide only the values that are different:

with:

environment: prod

command: plan

This creates a useful separation.

The generated workflows define when and where Terraform should run.

The reusable workflow defines how Terraform should run.

If authentication changes, a Terraform version needs to be upgraded, or another validation step is introduced, the change can be made once in the reusable workflow instead of modifying every environment workflow.

For pull requests, Terraform runs a plan.

For changes pushed to main, Terraform runs an apply.

The normal flow is:

Pull request -> Terraform plan -> review -> merge -> push to main -> Terraform apply

This allows infrastructure changes to be reviewed before they are deployed.

The same setup can also react to pull request approvals and execute another plan after a review is submitted.

This can be useful when additional changes have been pushed during the review process and the infrastructure should be checked again before merging.

Plans and applies should not necessarily behave the same way when multiple workflow runs are started.

For a Terraform plan, a newer commit usually makes the previous plan outdated.

For example:

Commit A -> plan starts

Commit B -> old plan is cancelled -> new plan starts

The concurrency group can include both the environment and the pull request number:

prod-plan-42

This ensures that only the latest plan for that pull request remains active.

Terraform applies need more careful handling.

If an apply is already modifying an environment, it should not normally be cancelled just because another commit reaches main.

Instead:

Apply 1 -> completes -> Apply 2 starts

Using an environment-specific concurrency group such as:

prod-apply

prevents two deployments from modifying the same Terraform state at the same time.

There is still one problem if the workflow generator has to be executed manually:

someone eventually forgets to run it.

For that reason, workflow generation can be connected to a Git pre-commit hook.

When a developer runs:

git commit

the pre-commit hook executes the Python generator before the commit is finalized.

The process becomes:

Terraform changes -> git commit -> pre-commit hook -> workflow generator

A simplified local hook configuration could look like this:

repos:

  - repo: local

    hooks:

      - id: generate-terraform-workflows

        name: Generate Terraform workflows

        entry: python3 scripts/generate_workflows.py

        language: system

        pass_filenames: false

This means generating the workflows becomes part of the normal Git workflow rather than another command developers need to remember.

If a new environment is introduced or its Terraform dependencies change, the corresponding workflow can be regenerated automatically during the commit process.

There is one important detail here.

If the generator creates or modifies a workflow file, that file is not automatically added to the Git index.

In that case, the generated changes need to be reviewed and staged:

git add .github/workflows/

git commit

The hook runs again on the next commit attempt. Since the generated workflows are now up to date and staged, the commit can continue.

The complete process becomes:

Terraform changes -> git commit -> pre-commit hook -> workflow generator -> generated files changed -> review -> git add -> git commit

This behavior is useful because generated CI/CD changes remain visible to the developer before they are committed.

The generated YAML files can still be committed to Git, which is useful because workflow changes remain visible during code review.

A pull request can therefore show both the Terraform change and the resulting CI/CD change.

The biggest advantage is not simply having fewer YAML files to write manually.

It is having fewer independent sources of truth.

With manually maintained workflows, adding an environment may involve copying another YAML file and changing the environment name, working directory, path filters, concurrency group, Terraform command, and other inputs.

That works until one of those values is missed.

With generated workflows, the process is closer to:

Repository structure + Terraform dependencies + workflow rules -> generated workflows

The environment-specific workflow becomes an output instead of something developers need to design and maintain separately.

It also makes larger repositories easier to extend.

Adding another Terraform environment does not mean starting another GitHub Actions workflow from scratch.

There are still areas where this approach can be improved.

Recursive Terraform Dependency Detection

Dependency detection is one of them.

An environment may reference one Terraform module that internally references another module.

A simple scan of the environment itself may detect the first dependency but not the second one.

For example:

prod -> database module -> networking module

A more advanced implementation could recursively resolve these relationships and build a complete Terraform dependency graph.

This would make the generated path filters even more precise.

Other improvements could include:

  • validating generated workflows in CI
  • automatically removing workflow files when environments are deleted
  • checking that generated files are up to date
  • adding tests for dependency discovery

Maintaining a few GitHub Actions workflows for Terraform manually is straightforward.

Maintaining the same pattern across a growing number of Terraform environments is where it starts to become repetitive.

Generating the environment workflows allows the repository structure and Terraform dependencies to drive the CI/CD configuration.

The environment is discovered automatically, its dependencies determine the relevant path filters, and the resulting workflow delegates Terraform execution to a shared reusable workflow.

Using a pre-commit hook completes the process by making generation part of the normal development flow:

Terraform change -> git commit -> generate workflows -> review and stage changes -> git commit -> GitHub Actions -> Terraform

The result is a setup that requires less duplicated configuration, keeps GitHub Actions workflows consistent across Terraform environments, and makes adding new infrastructure environments much easier to manage.

Keep an eye on the ITGix blogs for the next chapter.

Newsletter for Tech experts

Signal, not noise -

straight to your inbox.

Join 12,000+ engineers and business leaders getting field notes on SRE, DevOps and cloud- native reliability.

Deep-dive tech blogs & case studies
Emerging tech, curated

Your Work Email

We respect your inbox. Read our Privecy Policy

More Posts

“Prometheus-compatible” is one of the least informative phrases in observability marketing. Usually, it means: we’ll accept your scrape endpoint. Point it at us, we’ll store the series, and from then...
Reading
The ITGix Application Development Platform empowers teams to deploy and manage application infrastructure with greater simplicity, flexibility, and control. Designed to make cloud infrastructure more accessible, the platform enables users...
Reading
Get In Touch
ITGix provides you with expert consultancy and tailored DevOps services to accelerate your business growth.
Newsletter for
Tech Experts
Join 12,000+ business leaders and engineers who receive blogs, e-Books, and case studies on emerging technology.