Python Curriculum
Running Terraform From Python
Infrastructure as Code (IaC) allows you to define virtual machines, network configurations, database instances, and DNS records in declarative configuration files. Terraform is the industry standard for cloud-agnostic IaC.
While developers run Terraform from the CLI, DevOps automation often requires orchestration:
- Triggering infrastructure builds in response to API requests.
- Programmatically generating dynamic workspaces for sandbox environments.
- Destroying idle environments automatically after a lease period.
Using Python to run Terraform connects your business logic directly to your infrastructure lifecycle. In this guide, we will cover how to run Terraform subcommands (init, plan, apply, destroy) programmatically using Python's subprocess module, handle exit codes correctly (including Terraform's spec-compliant detail changes), and wrap operations in the python-terraform library.
The Execution Workflow
1. Running Terraform using Python's subprocess Module
The most direct and dependency-free way to run Terraform is using Python's built-in subprocess module. We use subprocess.run() to execute commands and capture stdout and stderr for processing.
Specifying Safe Arguments
To prevent command injection, always pass command arguments as lists of strings (e.g. ["terraform", "apply", "-auto-approve"]) rather than passing raw command strings with shell=True.
Here is the implementation of a basic runner class:
2. Advanced: Detailed Exit Codes during plan
By default, standard commands return 0 for success and non-zero for failures. However, when auditing changes, you want to distinguish if a plan contains changes, has no changes, or failed.
To do this, pass the -detailed-exitcode flag to the plan command. Under this mode, Terraform returns:
0: Succeeded with empty plan (no changes to apply).1: Command failed due to error.2: Succeeded and found changes (modifications, additions, or destructions exist).
Here is how to handle these exit codes:
3. Wrapping Command executions in python-terraform
If you prefer an object-oriented Python wrapper that abstracts standard command-line flags, you can use the third-party python-terraform package.
Install the library:
Here is how you use it to execute workflows:
4. Managing Workspaces Programmatically
Workspaces allow you to isolate multiple states within the same configuration folder (e.g. staging vs. production).
Summary
Running Terraform from Python bridges your application logical flows to your hardware resources. By wrapping CLI commands securely using subprocess lists, checking detailed exit codes, and leveraging wrappers like python-terraform, you can automate infrastructure provisioning. In the next section, we will cover how to parse Terraform output in Python.