Skip to content

TerraformCommand

Import TerraformCommand from the package root:

from libterraform import TerraformCommand

Most high-level methods return a CommandResult.

Threading

TerraformCommand can be called from multiple Python threads. Calls are thread-safe, but Terraform CLI execution is serialized inside the shared library because Terraform uses process-wide state. Use separate processes for true parallel Terraform operations.

CommandResult

CommandResult exposes:

  • retcode: Terraform return code.
  • value: parsed JSON or raw stdout, depending on the method and json=.
  • error: stderr.
  • json: whether stdout was parsed as JSON.

Parameter Rules

Common Parameters

Many TerraformCommand methods share the following keyword arguments:

Parameter Description
check Whether to check the Terraform return code. When True, raises TerraformCommandError if the return code is not 0 or 2.
json Whether to request or parse JSON output. Methods that support JSON typically default to True.
no_color Whether to add -no-color to suppress ANSI color codes in output.
input Whether to allow interactive prompts. Automation scenarios typically set this to False.
lock Whether to hold a state lock during the operation.
lock_timeout Duration to wait when acquiring a state lock.
vars A dict of Terraform variables, converted to multiple -var=key=value flags.
var_files A list of variable files, converted to multiple -var-file=... flags.
target Target resource address or list of addresses.
parallelism Number of concurrent Terraform operations.
state Path to the state file.
options Additional Terraform options. Underscores are converted to hyphens, e.g. detailed_exitcode becomes -detailed-exitcode.

Option Conversion

  • True / False are converted to Terraform's lowercase boolean strings.
  • ... (Ellipsis) is treated as a value-less flag, e.g. {"json": ...} produces -json.
  • Lists are expanded to multiple flags with the same name.
  • Dicts are expanded to -name=key=value form.

libterraform.cli.TerraformCommand

Terraform command line.

https://developer.hashicorp.com/terraform

run classmethod

run(
    cmd: CmdType,
    args: Optional[Sequence[str]] = None,
    options: Optional[dict] = None,
    chdir=None,
    check: bool = False,
    json=False,
) -> Tuple[int, str, str]

Run command with args and return a tuple (retcode, stdout, stderr).

The returned object will have attributes retcode, value, json.

If check is True and the return code was non 0 or 2, it raises a TerraformCommandError. The TerraformCommandError object will have the return code in the retcode attribute, and stdout & stderr attributes.

Parameters:

Name Type Description Default
cmd CmdType

Terraform command

required
args Optional[Sequence[str]]

Terraform command argument list

None
options Optional[dict]

Terraform command options Each key in options should be snake format, and will be convert to command option key automatically. ex. no_color will be converted to -no-color. Each value in options will be converted to appropriate command value automatically. The conversion rules for values are as follows: value ... will be regarded as flag option. ex. {"json": ...} -> -json boolean value will be converted to lower boolean. ex. {"backend": True} -> -backend=true list value will be converted to multi pairs. ex. {"var": ["Name1=xx", "Name2=xx"]} -> -var Name1=xx -var Name2=xx

None
chdir

Switch to a different working directory before executing the given subcommand.

None
check bool

Whether to check return code.

False
json

Whether to load stdout as json. Only partial commands support json param.

False

Returns:

Type Description
Tuple[int, str, str]

Command result tuple (retcode, stdout, stderr).

version

version(
    check: bool = False, json: bool = True, **options
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/version

Displays the version of Terraform and all installed plugins.

By default, this assumes you want to get json output

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
options

More command options.

{}

init

init(
    check: bool = False,
    backend: bool = None,
    backend_config: Union[str, List[str]] = None,
    force_copy: bool = None,
    from_module: str = None,
    get: bool = None,
    input: bool = False,
    lock: bool = None,
    lock_timeout: str = None,
    no_color: bool = True,
    plugin_dirs: List[str] = None,
    reconfigure: bool = None,
    migrate_state: bool = None,
    upgrade: bool = None,
    lockfile: str = None,
    ignore_remote_version: bool = None,
    test_directory: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/init

Initialize a new or existing Terraform working directory by creating initial files, loading any remote state, downloading modules, etc.

This is the first command that should be run for any new or existing Terraform configuration per machine. This sets up all the local data necessary to run Terraform that is typically not committed to version control.

This command is always safe to run multiple times. Though subsequent runs may give errors, this command will never delete your configuration or state. Even so, if you have important information, please back it up prior to running this command, just in case.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
backend bool

False to disable backend or HCP Terraform initialization for this configuration and use what was previously initialized instead.

None
backend_config Union[str, List[str]]

Configuration to be merged with what is in the configuration file's 'backend' block. This can be either a path to an HCL file with key/value assignments (same format as terraform.tfvars) or a 'key=value' format, and can be specified multiple times. The backend type must be in the configuration itself

None
force_copy bool

Suppress prompts about copying state data when initializating a new state backend. This is equivalent to providing a "yes" to all confirmation prompts.

None
from_module str

Copy the contents of the given module into the target directory before initialization.

None
get bool

False to disable downloading modules for this configuration.

None
input bool

False to disable interactive prompts. Note that some actions may require interactive prompts and will error if input is disabled.

False
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
no_color bool

True to output not contain any color.

True
plugin_dirs List[str]

Directories containing plugin binaries. This overrides all default search paths for plugins, and prevents the automatic installation of plugins.

None
reconfigure bool

Reconfigure a backend, ignoring any saved configuration.

None
migrate_state bool

Reconfigure a backend, and attempt to migrate any existing state.

None
upgrade bool

Install the latest module and provider versions allowed within configured constraints, overriding the default behavior of selecting exactly the version recorded in the dependency lockfile.

None
lockfile str

Set a dependency lockfile mode. Currently only "readonly" is valid.

None
ignore_remote_version bool

A rare option used for HCP Terraform and the remote backend only. Set this to ignore checking that the local and remote Terraform versions use compatible state representations, making an operation proceed even when there is a potential mismatch. See the documentation on configuring Terraform with HCP Terraform or Terraform Enterprise for more information.

None
test_directory str

Set the Terraform test directory, defaults to "tests".

None
options

More command options.

{}

validate

validate(
    check: bool = False,
    json: bool = True,
    no_color: bool = True,
    no_test: bool = None,
    test_directory: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/validate

Validate the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc.

Validate runs checks that verify whether a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state. It is thus primarily useful for general verification of reusable modules, including correctness of attribute names and value types.

It is safe to run this command automatically, for example as a post-save check in a text editor or as a test step for a re-usable module in a CI system.

Validation requires an initialized working directory with any referenced plugins and modules installed. To initialize a working directory for validation without accessing any configured remote backend, use: self.init(backend=False)

To verify configuration in the context of a particular run (a particular target workspace, input variable values, etc), use the self.plan() instead, which includes an implied validation check.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
no_color bool

True to output not contain any color.

True
no_test bool

If specified, Terraform will not validate test files.

None
test_directory str

Set the Terraform test directory, defaults to "tests".

None
options

More command options.

{}

plan

plan(
    check: bool = False,
    json: bool = True,
    destroy: bool = None,
    refresh_only: bool = None,
    refresh: bool = None,
    replace: Union[str, List[str]] = None,
    target: Union[str, List[str]] = None,
    vars: dict = None,
    var_files: List[str] = None,
    compact_warnings: bool = None,
    detailed_exitcode: bool = None,
    generate_config_out: str = None,
    input: bool = False,
    lock: bool = None,
    lock_timeout: str = None,
    no_color: bool = True,
    out: str = None,
    parallelism: int = None,
    state: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/plan

Generates a speculative execution plan, showing what actions Terraform would take to apply the current configuration. This command will not actually perform the planned actions.

You can optionally save the plan to a file, which you can then pass to the self.apply() to perform exactly the actions described in the plan.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
destroy bool

Select the "destroy" planning mode, which creates a plan to destroy all objects currently managed by this Terraform configuration instead of the usual behavior.

None
refresh_only bool

Select the "refresh only" planning mode, which checks whether remote objects still match the outcome of the most recent Terraform apply but does not propose any actions to undo any changes made outside of Terraform.

None
refresh bool

Skip checking for external changes to remote objects while creating the plan. This can potentially make planning faster, but at the expense of possibly planning against a stale record of the remote system state.

None
replace Union[str, List[str]]

Force replacement of a particular resource instance using its resource address. If the plan would've normally produced an update or no-op action for this instance, Terraform will plan to replace it instead. You can use this option multiple times to replace more than one object.

None
target Union[str, List[str]]

Limit the planning operation to only the given module, resource, or resource instance and all of its dependencies. You can use this option multiple times to include more than one object. This is for exceptional use only.

None
vars dict

Set variables in the root module of the configuration.

None
var_files List[str]

Load variable values from the given files, in addition to the default files terraform.tfvars and *.auto.tfvars.

None
compact_warnings bool

If Terraform produces any warnings that are not accompanied by errors, shows them in a more compact form that includes only the summary messages.

None
detailed_exitcode bool

Return detailed exit codes when the command exits. This will change the meaning of exit codes to: 0 - Succeeded, diff is empty (no changes) 1 - Errored 2 - Succeeded, there is a diff

None
generate_config_out str

(Experimental) If import blocks are present in configuration, instructs Terraform to generate HCL for any imported resources not already present. The configuration is written to a new file at PATH, which must not already exist. Terraform may still attempt to write configuration if the plan errors.

None
input bool

False to disable interactive prompts. Note that some actions may require interactive prompts and will error if input is disabled.

False
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
no_color bool

True to output not contain any color.

True
out str

Write a plan file to the given path. This can be used as input to the show or apply command.

None
parallelism int

Limit the number of concurrent operations. Defaults to 10.

None
state str

A legacy option used for the local backend only. See the local backend's documentation for more information.

None
options

More command options.

{}

query

query(
    check: bool = False,
    json: bool = True,
    vars: dict = None,
    var_files: List[str] = None,
    generate_config_out: str = None,
    no_color: bool = True,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/query

Queries remote infrastructure for resources using .tfquery.hcl files.

Terraform 1.13 registers this command only when experimental features are enabled.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
vars dict

Set variables in the query file of the configuration.

None
var_files List[str]

Load variable values from the given files, in addition to the default files terraform.tfvars and *.auto.tfvars.

None
generate_config_out str

Instructs Terraform to generate import and resource blocks for found results.

None
no_color bool

True to output not contain any color.

True
options

More command options.

{}

show

show(
    path: str = None,
    check: bool = False,
    json: bool = True,
    no_color: bool = True,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/show

Reads and outputs a Terraform state or plan file in a human-readable form. If no path is specified, the current state will be shown.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
path str

Terraform state or plan file path.

None
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
no_color bool

True to output not contain any color.

True
options

More command options.

{}

apply

apply(
    plan: str = None,
    check: bool = False,
    json: bool = True,
    auto_approve: bool = True,
    backup: str = None,
    compact_warnings: bool = None,
    input: bool = False,
    lock: bool = None,
    lock_timeout: str = None,
    no_color: bool = True,
    parallelism: int = None,
    state: str = None,
    state_out: str = None,
    destroy: bool = None,
    vars: dict = None,
    var_files: List[str] = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/apply

Creates or updates infrastructure according to Terraform configuration files in the current directory.

By default, Terraform will generate a new plan and present it for your approval before taking any action. You can optionally provide a plan file created by a previous call to self.plan(), in which case Terraform will take the actions described in that plan without any confirmation prompt.

If you don't provide a saved plan file then this command will also accept all of the plan-customization options accepted by the terraform plan command.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
plan str

Terraform plan file path.

None
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
auto_approve bool

Skip interactive approval of plan before applying.

True
backup str

Path to backup the existing state file before modifying. Defaults to the state_out path with ".backup" extension. Set to "-" to disable backup.

None
compact_warnings bool

If Terraform produces any warnings that are not accompanied by errors, shows them in a more compact form that includes only the summary messages.

None
input bool

False to disable interactive prompts. Note that some actions may require interactive prompts and will error if input is disabled.

False
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
no_color bool

True to output not contain any color.

True
parallelism int

Limit the number of concurrent operations. Defaults to 10.

None
state str

Path to read and save state (unless state_out is specified). Defaults to "terraform.tfstate".

None
state_out str

Path to write state to that is different than state. This can be used to preserve the old state.

None
destroy bool

Select the "destroy" planning mode, which creates a plan to destroy all objects currently managed by this Terraform configuration instead of the usual behavior.

None
vars dict

Set variables in the root module of the configuration. With Terraform 1.10 and later, this can also provide apply-time ephemeral variables when applying a saved plan file.

None
var_files List[str]

Load variable values from the given files, in addition to the default files terraform.tfvars and *.auto.tfvars.

None
options

More command options.

{}

destroy

destroy(
    check: bool = False,
    json: bool = True,
    auto_approve: bool = True,
    backup: str = None,
    compact_warnings: bool = None,
    input: bool = False,
    lock: bool = None,
    lock_timeout: str = None,
    no_color: bool = True,
    parallelism: int = None,
    state: str = None,
    state_out: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/destroy

Destroy Terraform-managed infrastructure.

By default, this assumes you want to get json output.

This command is a convenience alias for: terraform apply -destroy

This command also accepts many of the plan-customization options accepted by the terraform plan command. For more information on those options, run: terraform plan -help

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
auto_approve bool

Skip interactive approval of plan before applying.

True
backup str

Path to backup the existing state file before modifying. Defaults to the state_out path with ".backup" extension. Set to "-" to disable backup.

None
compact_warnings bool

If Terraform produces any warnings that are not accompanied by errors, shows them in a more compact form that includes only the summary messages.

None
input bool

False to disable interactive prompts. Note that some actions may require interactive prompts and will error if input is disabled.

False
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
no_color bool

True to output not contain any color.

True
parallelism int

Limit the number of concurrent operations. Defaults to 10.

None
state str

Path to read and save state (unless state_out is specified). Defaults to "terraform.tfstate".

None
state_out str

Path to write state to that is different than state. This can be used to preserve the old state.

None
options

More command options.

{}

fmt

fmt(
    dir: Union[str, List[str]] = None,
    check: bool = False,
    no_color: bool = True,
    list: bool = None,
    write: bool = None,
    diff: bool = None,
    check_input: bool = None,
    recursive: bool = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/fmt

Rewrites all Terraform configuration files to a canonical format. All configuration files (.tf), variables files (.tfvars), and testing files (.tftest.hcl) are updated. JSON files (.tf.json, .tfvars.json, or .tftest.json) are not modified.

By default, fmt scans the current directory for configuration files. If you provide a directory for the target argument, then fmt will scan that directory instead. If you provide a file, then fmt will process just that file. If you provide a single dash ("-"), then fmt will read from standard input (STDIN).

If DIR is not specified then the current working directory will be used. If DIR is "-" then content will be read from STDIN. The given content must be in the Terraform language native syntax; JSON is not supported.

Parameters:

Name Type Description Default
dir Union[str, List[str]]

Directory which Terraform configuration files located.

None
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
list bool

False to not list files whose formatting differs (always disabled if using STDIN)

None
write bool

False to not write to source files (always disabled if using STDIN or checkout_input=True)

None
diff bool

Display diffs of formatting changes

None
check_input bool

Check if the input is formatted. Exit status will be 0 if all input is properly formatted and non-zero otherwise.

None
recursive bool

Also process files in subdirectories. By default, only the given directory (or current directory) is processed.

None
options

More command options.

{}

force_unlock

force_unlock(
    lock_id: str,
    check: bool = False,
    no_color: bool = True,
    force: bool = True,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/force-unlock

Manually unlock the state for the defined configuration.

This will not modify your infrastructure. This command removes the lock on the state for the current workspace. The behavior of this lock is dependent on the backend being used. Local state files cannot be unlocked by another process.

Parameters:

Name Type Description Default
lock_id str

Lock ID.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
force bool

True to not ask for input for unlock confirmation.

True
options

More command options.

{}

get

get(
    check: bool = False,
    no_color: bool = True,
    update: bool = None,
    test_directory: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/get

Downloads and installs modules needed for the configuration in the current working directory.

This recursively downloads all modules needed, such as modules imported by modules imported by the root and so on. If a module is already downloaded, it will not be redownloaded or checked for updates unless the -update flag is specified.

Module installation also happens automatically by default as part of the "terraform init" command, so you should rarely need to run this command separately.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
update bool

Check already-downloaded modules for available updates and install the newest versions available.

None
test_directory str

Set the Terraform test directory, defaults to "tests".

None
options

More command options.

{}

graph

graph(
    check: bool = False,
    no_color: bool = True,
    plan: str = None,
    draw_cycles: bool = None,
    type: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/graph

Produces a representation of the dependency graph between different objects in the current configuration and state.

By default the graph shows a summary only of the relationships between resources in the configuration, since those are the main objects that have side-effects whose ordering is significant. You can generate more detailed graphs reflecting Terraform's actual evaluation strategy by specifying the -type=TYPE option to select an operation type.

The graph is presented in the DOT language. The typical program that can read this format is GraphViz, but many web services are also available to read this format.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
plan str

Render graph using the specified plan file instead of the configuration in the current directory. Implies type=apply.

None
draw_cycles bool

True to highlight any cycles in the graph with colored edges. This helps when diagnosing cycle errors. This option is supported only when illustrating a real evaluation graph, selected using the type=TYPE option.

None
type str

Type of operation graph to output. Can be: plan, plan-refresh-only, plan-destroy, or apply. By default Terraform just summarizes the relationships between the resources in your configuration, without any particular operation in mind. Full operation graphs are more detailed but therefore often harder to read.

None
options

More command options.

{}

import_resource

import_resource(
    addr: str,
    id: str,
    check: bool = False,
    config: str = None,
    input: bool = False,
    lock: bool = None,
    lock_timeout: str = None,
    no_color: bool = True,
    vars: dict = None,
    var_files: List[str] = None,
    ignore_remote_version: bool = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/import

Import existing infrastructure into your Terraform state.

This will find and import the specified resource into your Terraform state, allowing existing infrastructure to come under Terraform management without having to be initially created by Terraform.

The current implementation of Terraform import can only import resources into the state. It does not generate configuration. A future version of Terraform will also generate configuration.

The ADDR specified is the address to import the resource to. Please see the documentation online for resource addresses. The ID is a resource-specific ID to identify that resource being imported. Please reference the documentation for the resource type you're importing to determine the ID syntax to use. It typically matches directly to the ID that the provider uses.

This command will not modify your infrastructure, but it will make network requests to inspect parts of your infrastructure relevant to the resource being imported.

Parameters:

Name Type Description Default
addr str

The address to import the resource to. Please see the documentation online for resource addresses.

required
id str

The id is a resource-specific ID to identify that resource being imported. Please reference the documentation for the resource type you're importing to determine the ID syntax to use. It typically matches directly to the ID that the provider uses.

required
check bool

Whether to check return code.

False
config str

Path to a directory of Terraform configuration files to use to configure the provider. Defaults to pwd. If no config files are present, they must be provided via the input prompts or env vars.

None
input bool

False to disable interactive prompts. Note that some actions may require interactive prompts and will error if input is disabled.

False
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
no_color bool

True to output not contain any color.

True
vars dict

Set variables in the Terraform configuration. This is only useful with the "config" option.

None
var_files List[str]

Load variable values from the given files, in addition to the default files terraform.tfvars and *.auto.tfvars.

None
ignore_remote_version bool

A rare option used for the remote backend only. See the remote backend documentation for more information.

None
options

More command options.

{}

output

output(
    name: str = None,
    check: bool = False,
    json: bool = True,
    no_color: bool = True,
    state: str = None,
    raw: bool = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/output

Reads an output variable from a Terraform state file and prints the value. With no additional arguments, output will display all the outputs for the root module. If name is not specified, all outputs are printed.

Parameters:

Name Type Description Default
name str

Name of output variable.

None
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
no_color bool

True to output not contain any color.

True
state str

Path to the state file to read. Defaults to "terraform.tfstate". Ignored when remote state is used.

None
raw bool

For value types that can be automatically converted to a string, will print the raw string directly, rather than a human-oriented representation of the value.

None
options

More command options.

{}

modules

modules(
    check: bool = False, json: bool = True, **options
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/modules

Prints source and version data about all declared modules in Terraform configuration for the current working directory.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
options

More command options.

{}

providers

providers(
    subcmd: str = None,
    args: Sequence[str] = None,
    check: bool = False,
    no_color: bool = True,
    json: bool = False,
    test_directory: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/providers

Prints out a tree of modules in the referenced configuration annotated with their provider requirements.

This provides an overview of all of the provider requirements across all referenced modules, as an aid to understanding why particular provider plugins are needed and why particular versions are selected.

Parameters:

Name Type Description Default
subcmd str

Sub commands: lock, mirror and schema.

None
args Sequence[str]

Args for command.

None
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
json bool

Whether to load stdout as json. Only valid when subcmd=schema.

False
test_directory str

Set the Terraform test directory, defaults to "tests".

None
options

More command options.

{}

providers_lock

providers_lock(
    *providers,
    check: bool = False,
    no_color: bool = True,
    fs_mirror: str = None,
    net_mirror: str = None,
    platform: Union[str, List[str]] = None,
    enable_plugin_cache: bool = False,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/providers/lock

Normally the dependency lock file (.terraform.lock.hcl) is updated automatically by "terraform init", but the information available to the normal provider installer can be constrained when you're installing providers from filesystem or network mirrors, and so the generated lock file can end up incomplete.

The "providers lock" subcommand addresses that by updating the lock file based on the official packages available in the origin registry, ignoring the currently-configured installation strategy.

After this command succeeds, the lock file will contain suitable checksums to allow installation of the providers needed by the current configuration on all of the selected platforms.

By default, this command updates the lock file for every provider declared in the configuration. You can override that behavior by providing one or more provider source addresses on the command line.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
fs_mirror str

Consult the given filesystem mirror directory instead of the origin registry for each of the given providers. This would be necessary to generate lock file entries for a provider that is available only via a mirror, and not published in an upstream registry. In this case, the set of valid checksums will be limited only to what Terraform can learn from the data in the mirror directory.

None
net_mirror str

Consult the given network mirror (given as a base URL) instead of the origin registry for each of the given providers. This would be necessary to generate lock file entries for a provider that is available only via a mirror, and not published in an upstream registry. In this case, the set of valid checksums will be limited only to what Terraform can learn from the data in the mirror indices.

None
platform Union[str, List[str]]

Choose a target platform to request package checksums for. By default, Terraform will request package checksums suitable only for the platform where you run this command. Use this option multiple times to include checksums for multiple target systems. Target names consist of an operating system and a CPU architecture. For example, "linux_amd64" selects the Linux operating system running on an AMD64 or x86_64 CPU. Each provider is available only for a limited set of target platforms.

None
enable_plugin_cache bool

Enable the usage of the globally configured plugin cache. This will speed up the locking process, but the providers wont be loaded from an authoritative source.

False
options

More command options.

{}

providers_mirror

providers_mirror(
    target_dir: str,
    check: bool = False,
    no_color: bool = True,
    platform: Union[str, List[str]] = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/providers/mirror

Populates a local directory with copies of the provider plugins needed for the current configuration, so that the directory can be used either directly as a filesystem mirror or as the basis for a network mirror and thus obtain those providers without access to their origin registries in the future.

The mirror directory will contain JSON index files that can be published along with the mirrored packages on a static HTTP file server to produce a network mirror. Those index files will be ignored if the directory is used instead as a local filesystem mirror.

Parameters:

Name Type Description Default
target_dir str

Choose which target directory to build a mirror for.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
platform Union[str, List[str]]

Choose which target platform to build a mirror for. By default, Terraform will obtain plugin packages suitable for the platform where you run this command. Use this flag multiple times to include packages for multiple target systems. Target names consist of an operating system and a CPU architecture. For example, "linux_amd64" selects the Linux operating system running on an AMD64 or x86_64 CPU. Each provider is available only for a limited set of target platforms.

None
options

More command options.

{}

providers_schema

providers_schema(
    check: bool = False, no_color: bool = True, **options
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/providers

Prints out a json representation of the schemas for all providers used in the current configuration.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
options

More command options.

{}

refresh

refresh(
    check: bool = False,
    json: bool = True,
    target: Union[str, List[str]] = None,
    vars: dict = None,
    var_files: List[str] = None,
    compact_warnings: bool = None,
    input: bool = False,
    lock: bool = None,
    lock_timeout: str = None,
    no_color: bool = True,
    parallelism: int = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/refresh

Update the state file of your infrastructure with metadata that matches the physical resources they are tracking.

This will not modify your infrastructure, but it can modify your state file to update metadata. This metadata might cause new changes to occur when you generate a plan or call apply next.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
json bool

Whether to load stdout as json.

True
target Union[str, List[str]]

Resource to target. Operation will be limited to this resource and its dependencies. This flag can be used multiple times.

None
vars dict

Set variables in the Terraform configuration.

None
var_files List[str]

Load variable values from the given files, in addition to the default files terraform.tfvars and *.auto.tfvars.

None
compact_warnings bool

If Terraform produces any warnings that are not accompanied by errors, shows them in a more compact form that includes only the summary messages.

None
input bool

False to disable interactive prompts. Note that some actions may require interactive prompts and will error if input is disabled.

False
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
no_color bool

True to output not contain any color.

True
parallelism int

Limit the number of concurrent operations. Defaults to 10.

None
options

More command options.

{}

state

state(
    subcmd: str,
    args: Sequence[str] = None,
    check: bool = False,
    no_color: bool = True,
    json: bool = False,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/state

This command has subcommands for advanced state management.

These subcommands can be used to slice and dice the Terraform state. This is sometimes necessary in advanced cases. For your safety, all state management commands that modify the state create a timestamped backup of the state prior to making modifications.

The structure and output of the commands is specifically tailored to work well with the common Unix utilities such as grep, awk, etc. We recommend using those tools to perform more advanced state tasks.

Parameters:

Name Type Description Default
subcmd str

Sub commands: identities, list, mv, pull, push, replace-provider, rm and show.

required
args Sequence[str]

Args for command.

None
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
json bool

Whether to load stdout as json.

False
options

More command options.

{}

state_list

state_list(
    *addrs,
    check: bool = False,
    no_color: bool = True,
    state: str = None,
    ids: Sequence[str] = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/state/list

List resources in the Terraform state.

An error will be returned if any of the resources or modules given as filter addresses do not exist in the state.

Parameters:

Name Type Description Default
addrs

Can be used to filter the instances by resource or module. If no pattern is given, all resource instances are listed. The addresses must either be module addresses or absolute resource addresses, such as: aws_instance.example module.example module.example.module.child module.example.aws_instance.example

()
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
state str

Path to a Terraform state file to use to look up Terraform-managed resources. By default, Terraform will consult the state of the currently-selected workspace.

None
ids Sequence[str]

Filters the results to include only instances whose resource types have an attribute named "id" whose value is in the given ids.

None
options

More command options.

{}

state_identities

state_identities(
    *addrs,
    check: bool = False,
    no_color: bool = True,
    state: str = None,
    identity_id: str = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/v1.12.x/commands/state

List the identities of resources in the Terraform state in JSON format.

The address argument can be used to filter the instances by resource or module. If no pattern is given, identities for all resource instances are listed.

Parameters:

Name Type Description Default
addrs

Can be used to filter the instances by resource or module. If no pattern is given, all resource identities are listed.

()
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
state str

Path to a Terraform state file to use to look up Terraform-managed resources. By default, Terraform will consult the state of the currently-selected workspace.

None
identity_id str

Filters the results to include only instances whose resource types have an attribute named "id" whose value equals the given string.

None
options

More command options.

{}

state_mv

state_mv(
    src: str,
    dst: str,
    check: bool = False,
    no_color: bool = True,
    dry_run: bool = None,
    lock: bool = None,
    lock_timeout: str = None,
    ignore_remote_version: bool = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/state/mv

This command will move an item matched by the address given to the destination address. This command can also move to a destination address in a completely different state file.

This can be used for simple resource renaming, moving items to and from a module, moving entire modules, and more. And because this command can also move data to a completely new state, it can also be used for refactoring one configuration into multiple separately managed Terraform configurations.

This command will output a backup copy of the state prior to saving any changes. The backup cannot be disabled. Due to the destructive nature of this command, backups are required.

If you're moving an item to a different state file, a backup will be created for each state file.

Parameters:

Name Type Description Default
src str

Source address of resource.

required
dst str

Destination address of resource.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
dry_run bool

True to print out what would've been moved but doesn't actually move anything.

None
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
ignore_remote_version bool

A rare option used for the remote backend only. See the remote backend documentation for more information.

None
options

More command options.

{}

state_pull

state_pull(
    check: bool = False, no_color: bool = True, **options
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/state/pull

Pull the state from its location, upgrade the local copy, and output it. As part of this process, Terraform will upgrade the state format of the local copy to the current version.

The primary use of this is for state stored remotely. This command will still work with local state but is less useful for this.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
options

More command options.

{}

state_push

state_push(
    path: str,
    check: bool = False,
    no_color: bool = True,
    force: bool = None,
    lock: bool = None,
    lock_timeout: str = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/state/push

Update remote state from a local state file at path. The command will protect you against writing an older serial or a different state file lineage unless you specify the"force" flag.

This command works with local state (it will overwrite the local state), but is less useful for this use case.

If PATH is "-", then this command will read the state to push from stdin. Data from stdin is not streamed to the backend: it is loaded completely (until pipe close), verified, and then pushed.

Parameters:

Name Type Description Default
path str

The path of the local state file.

required
check bool

Whether to check return code.

False
force bool

True to write the state even if lineages don't match or the remote serial is higher.

None
no_color bool

True to output not contain any color.

True
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
options

More command options.

{}

state_replace_provider

state_replace_provider(
    from_provider: str,
    to_provider: str,
    check: bool = False,
    no_color: bool = True,
    auto_approve: bool = True,
    lock: bool = None,
    lock_timeout: str = None,
    ignore_remote_version: bool = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/state/replace-provider

Replace provider for resources in the Terraform state.

Parameters:

Name Type Description Default
from_provider str

FROM_PROVIDER_FQN.

required
to_provider str

TO_PROVIDER_FQN.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
auto_approve bool

Skip interactive approval.

True
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
ignore_remote_version bool

A rare option used for the remote backend only. See the remote backend documentation for more information.

None
options

More command options.

{}

state_rm

state_rm(
    *addrs,
    check: bool = False,
    no_color: bool = True,
    dry_run: bool = None,
    backup: str = None,
    lock: bool = None,
    lock_timeout: str = None,
    state: str = None,
    ignore_remote_version: bool = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/state/rm

Remove one or more items from the Terraform state, causing Terraform to "forget" those items without first destroying them in the remote system.

This command removes one or more resource instances from the Terraform state based on the addresses given. You can view and list the available instances with "terraform state list".

If you give the address of an entire module then all of the instances in that module and any of its child modules will be removed from the state.

If you give the address of a resource that has "count" or "for_each" set, all of the instances of that resource will be removed from the state.

Parameters:

Name Type Description Default
addrs

The address list of resources.

()
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
dry_run bool

Path where Terraform should write the backup state.

None
backup str

True to print out what would've been moved but doesn't actually move anything.

None
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
state str

Path to the state file to update. Defaults to the current workspace state.

None
ignore_remote_version bool

Continue even if remote and local Terraform versions are incompatible. This may result in an unusable workspace, and should be used with extreme caution.

None
options

More command options.

{}

state_show

state_show(
    addr: str,
    check: bool = False,
    no_color: bool = True,
    state: str = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/state/show

Shows the attributes of a resource in the Terraform state.

This command shows the attributes of a single resource in the Terraform state. The address argument must be used to specify a single resource. You can view the list of available resources with "terraform state list".

Parameters:

Name Type Description Default
addr str

The address of resource.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
state str

Path to the state file to update. Defaults to the current workspace state.

None
options

More command options.

{}

stacks

stacks(
    args: Sequence[str] = None,
    check: bool = False,
    no_color: bool = True,
    plugin_cache_dir: str = None,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/stacks

Executes Terraform Stacks subcommands.

The available subcommands depend on the Stacks plugin implementation.

Parameters:

Name Type Description Default
args Sequence[str]

Args for the Stacks plugin command.

None
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
plugin_cache_dir str

Override the Stacks plugin cache directory.

None
options

More command options.

{}

taint

taint(
    addr: str,
    check: bool = False,
    no_color: bool = True,
    allow_missing_config: bool = None,
    lock: bool = None,
    lock_timeout: str = None,
    ignore_remote_version: bool = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/taint

Terraform uses the term "tainted" to describe a resource instance which may not be fully functional, either because its creation partially failed or because you've manually marked it as such using this command.

This will not modify your infrastructure directly, but subsequent Terraform plans will include actions to destroy the remote object and create a new object to replace it.

You can remove the "taint" state from a resource instance using the "terraform untaint" command.

The address is in the usual resource address syntax, such as: aws_instance.foo aws_instance.bar[1] module.foo.module.bar.aws_instance.baz

Use your shell's quoting or escaping syntax to ensure that the address will reach Terraform correctly, without any special interpretation.

Parameters:

Name Type Description Default
addr str

The address of resource.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
allow_missing_config bool

True to regard the command will succeed (exit code 0) even if the resource is missing.

None
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
ignore_remote_version bool

A rare option used for the remote backend only. See the remote backend documentation for more information.

None
options

More command options.

{}

untaint

untaint(
    addr: str,
    check: bool = False,
    no_color: bool = True,
    allow_missing_config: bool = None,
    lock: bool = None,
    lock_timeout: str = None,
    ignore_remote_version: bool = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/untaint

Terraform uses the term "tainted" to describe a resource instance which may not be fully functional, either because its creation partially failed or because you've manually marked it as such using the "terraform taint" command.

This command removes that state from a resource instance, causing Terraform to see it as fully-functional and not in need of replacement.

This will not modify your infrastructure directly. It only avoids Terraform planning to replace a tainted instance in a future operation.

Parameters:

Name Type Description Default
addr str

The address of resource.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
allow_missing_config bool

True to regard the command will succeed (exit code 0) even if the resource is missing.

None
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
ignore_remote_version bool

A rare option used for the remote backend only. See the remote backend documentation for more information.

None
options

More command options.

{}

test

test(
    check: bool = False,
    vars: dict = None,
    var_files: List[str] = None,
    no_color: bool = True,
    cloud_run: str = None,
    filter: Union[str, List[str]] = None,
    json: bool = True,
    junit_xml: str = None,
    test_directory: str = None,
    run_parallelism: int = None,
    verbose: bool = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/test

Executes automated integration tests against the current Terraform configuration.

Terraform will search for .tftest.hcl files within the current configuration and testing directories. Terraform will then execute the testing run blocks within any testing files in order, and verify conditional checks and assertions against the created infrastructure.

This command creates real infrastructure and will attempt to clean up the testing infrastructure on completion. Monitor the output carefully to ensure this cleanup process is successful.

By default, this assumes you want to get json output.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
vars dict

Set variables in the root module of the configuration.

None
var_files List[str]

Load variable values from the given file, in addition to the default files terraform.tfvars and *.auto.tfvars.

None
no_color bool

True to output not contain any color.

True
cloud_run str

If specified, Terraform will execute this test run remotely using HCP Terraform or Terraform Enterpise. You must specify the source of a module registered in a private module registry as the argument to this flag. This allows Terraform to associate the cloud run with the correct HCP Terraform or Terraform Enterprise module and organization.

None
json bool

Whether to load stdout as json.

True
junit_xml str

Write a JUnit XML test report to the given file.

None
test_directory str

Set the Terraform test directory, defaults to "tests".

None
run_parallelism int

Limit the number of test runs that can execute in parallel within a file. Defaults to 10.

None
verbose bool

Print the plan or state for each test run block as it executes.

None
options

More command options.

{}

workspace

workspace(
    subcmd: str,
    args: Sequence[str] = None,
    check: bool = False,
    no_color: bool = True,
    **options,
) -> CommandResult

Refer to https://developer.hashicorp.com/terraform/cli/commands/workspace

new, list, show, select and delete Terraform workspaces.

Parameters:

Name Type Description Default
subcmd str

Sub commands: list, mv, pull, push, replace-provider, rm and show.

required
args Sequence[str]

Args for command.

None
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
options

More command options.

{}

workspace_new

workspace_new(
    name: str,
    check: bool = False,
    no_color: bool = True,
    lock: bool = None,
    lock_timeout: str = None,
    state: str = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/workspace/new

Create a new Terraform workspace.

Parameters:

Name Type Description Default
name str

Workspace name.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
state str

Copy an existing state file into the new workspace.

None
options

More command options.

{}

workspace_list

workspace_list(
    check: bool = False, no_color: bool = True, **options
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/workspace/list

List Terraform workspaces.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
options

More command options.

{}

workspace_show

workspace_show(
    check: bool = False, no_color: bool = True, **options
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/workspace/show

Show the name of the current workspace.

Parameters:

Name Type Description Default
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
options

More command options.

{}

workspace_select

workspace_select(
    name: str,
    check: bool = False,
    no_color: bool = True,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/workspace/select

Select a different Terraform workspace.

Parameters:

Name Type Description Default
name str

Workspace name.

required
check bool

Whether to check return code.

False
no_color bool

True to output not contain any color.

True
options

More command options.

{}

workspace_delete

workspace_delete(
    name: str,
    check: bool = False,
    no_color: bool = True,
    force: bool = None,
    lock: bool = None,
    lock_timeout: str = None,
    **options,
)

Refer to https://developer.hashicorp.com/terraform/cli/commands/workspace/delete

Delete a Terraform workspace.

Parameters:

Name Type Description Default
name str

Workspace name.

required
check bool

Whether to check return code.

False
no_color bool

True to remove even a non-empty workspace.

True
force bool

True to output not contain any color.

None
lock bool

False to not hold a state lock during backend migration. This is dangerous if others might concurrently run commands against the same workspace.

None
lock_timeout str

Duration to retry a state lock.

None
options

More command options.

{}