liveBook · Manning

Client library

As explained in Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu

A client library is a software library that provides programmatic interfaces for invoking and interacting with another system.

A client library gives Python code a programmatic way to drive Terraform or OpenTofu. It centralizes workspace settings, executable selection, logging, environment variables, command execution, and result handling. section 11.1.2

A practical Terraform client stores:

  • The working directory that selects the infrastructure code. section 11.1.2
  • The tofu or terraform binary, log level, and environment variables. section 11.1.2
  • Command output, error output, and return codes, with helpers for JSON and JSONL parsing. section 11.1.2

Creating a configured client

from tofupy import Tofu workspace = Tofu( cwd="/path/to/terraform/workspace", log_level="DEBUG", binary="terraform", ) The client can then run commands in the selected workspace, capture their output, and raise detailed errors when execution fails. section 11.1.2

Listing 11.1 Initializer in tofupy/tofu.py
import os                                                  #1
to use.
import shutil  # ANC
from pathlib import Path  # ANC
from typing import Dict  # ANC
 
 
class Tofu:                                                #2
    cwd: str | Path                                        #3
    binary_path: str                                       #4
    log_level: str                                         #5
    env: Dict[str, str]                                    #6
 
    def __init__(                                          #7
        self,                                              #8
        cwd: str = os.getcwd(),                            #9
        binary: str = "tofu",                              #10
        log_level: str = "ERROR",                          #11
        env: Dict[str, str] = {},                          #12
    ):
        self.cwd = cwd                                     #13
        self.log_level = log_level                         #13
        self.env = env                                     #13
        self.binary_path = shutil.which(binary)            #14
        if not self.binary_path:                           #15
            raise FileNotFoundError(                       #16
                f"Could not find {binary}, please make sure it is 
installed."
            )
#1 Just like with Go, Python needs you to import packages.
#2 Our main class will be called Tofu, since that’s our default binary.
#3 The working directory defines the code Terraform will run against.
#4 We need to save the binary path to run the commands.
#5 The log level will be used to set the verboseness of the logs.
#6 Our users can set environment variables to pass to the commands.
#7 This is a constructor, which is run when new instances are created.
#8 The first argument of a method is always a reference to the instance itself.
#9 The working directory is optional, defaulting to the current directory.
#10 We default to the tofu binary, but users can change it.
#11 The log level is optional, defaulting to ERROR.
#12 Environment variables are optional.
#13 We save these values to use later.
#14 We find the binary path using shutil.
#15 If the binary path is not found, we raise an error.
#16 This exception is built in to Python.

Inspect the initializer to see how the working directory, executable, logging level, and environment become client state. section 11.1.2

How Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu covers it

How deep it goes
Explains initialization, subprocess execution, structured results, and version checks, but stops short of a complete command API.
Examples
Uses a Tofu initializer, a configured Terraform workspace, command results, and JSON or JSONL parsing helpers.
What it assumes
Assumes Python class and command-line concepts while teaching the required executable, workspace, output, and return-code model.
What you can do after
Build a Python wrapper that configures, runs, parses, and diagnoses Terraform or OpenTofu commands.
How it connects
Connects Python with Terraform, OpenTofu, subprocess execution, environment variables, and JSON output.

Also explained in

Compare how 5 books explain client library →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu. The section links point to the parts of the book it draws on.