WintelGuy.com

Terraform Associate Exam Cram - Part 6

Use the core Terraform workflow

This is the Part 6 of the Terraform Associate Exam Cram. It covers the following Terraform Associate Certification exam objectives:

6a. Describe Terraform workflow ( Write -> Plan -> Create )

The core Terraform workflow includes the following main steps:

  • Write: Author Terraform configuration.
  • Initialize: Prepare workspace so Terraform can manage your configuration.
  • Plan: Preview the changes Terraform will make to the infrastructure.
  • Apply (Create/Modify/Destroy): Executes the plan to provision/update the infrastructure.

The workflow is iterative, any changes to the infra are deployed by following the same steps: update config → plan → apply again. It ensures predictable, reliable, and reproducible infrastructure deployments and changes.

It's common practice to store your configuration in a version controlled repository and execute Terraform workflow in a shared Continuous Integration (CI) environment.

Core Workflow Enhancements by HCP Terraform:

  • HCP Terraform provides a centralized and secure location for storing input variables and state while also enabling tight collaboration between config authors.
  • HCP Terraform makes the process of reviewing a speculative plan easier for team members.
  • After code merge, HCP Terraform presents the deployment plan to the team for review and approval.

Back to Top

6b. Initialize a Terraform working directory (terraform init)

The terraform init command performs the following actions to set up all the local data necessary to run Terraform:

  • Configures backend (state storage).
  • Installs modules.
  • Downloads providers.
  • Creates/updates the dependency lock file .terraform.lock.hcl.

It is the first command that should be run

  • for any new and, in certain cases, updated Terraform configuration, or
  • on any machine deploying a given Terraform configuration for the first time.

Usage: terraform init [options]

Options:

  • -backend=false - Disable backend or Terraform Cloud initialization for this configuration and use what was previously initialized instead. Aliases: -cloud=false
  • -backend-config=path - Configuration to be merged with what is in the configuration file's backend block. Can be either a path to an HCL file with key/value assignments (same format as terraform.tfvars) or a key=value format. Can be specified multiple times. The backend type must be in the configuration itself.
  • -force-copy - Suppress prompts about copying state data when initializing a new state backend. Equivalent to answering "yes" to all confirmation prompts.
  • -from-module=SOURCE - Copy the contents of the given module into the target directory before initialization.
  • -get=false - Disable downloading modules for this configuration.
  • -input=false - Disable interactive prompts. Some actions may require prompts and will error if input is disabled.
  • -lock=false - Don't hold a state lock during backend migration. Dangerous if others might concurrently run commands against the same workspace.
  • -lock-timeout=0s - Duration to retry a state lock.
  • -no-color - If specified, output won't contain any color.
  • -plugin-dir - Directory containing plugin binaries. Overrides all default search paths for plugins and prevents automatic installation. Can be used multiple times.
  • -reconfigure - Reconfigure a backend, ignoring any saved configuration.
  • -migrate-state - Reconfigure a backend and attempt to migrate any existing state.
  • -upgrade - Install the latest module and provider versions allowed within constraints, overriding the default behavior of selecting the version recorded in the dependency lockfile.
  • -lockfile=MODE - Set a dependency lockfile mode. Currently only readonly is valid.
  • -ignore-remote-version - Used for Terraform Cloud and remote backend only. Ignores checks that local and remote Terraform versions use compatible state representations, allowing operations to proceed even with potential mismatches. See Terraform Cloud documentation for details.

Re-run terraform init after updates to provider/backend configuration or changes to a module's source or version.

Related command:

terraform get [options] PATH - Recursively downloads and installs modules needed for the configuration given by PATH. If a module is already downloaded, it will not be redownloaded or checked for updates unless the -update flag is specified.

Back to Top

6c. Validate a Terraform configuration (terraform validate)

The terraform validate command checks whether a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state. It is 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.

Since terraform validate requires an initialized working directory with any referenced plugins and modules installed, the command must run after terraform init.

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

Usage: terraform validate [options]

Options:

  • -json - Produce output in a machine-readable JSON format, suitable for use in text editor integrations and other automated systems. Always disables color.
  • -no-color - If specified, output won't contain any color.

Back to Top

6d. Generate and review an execution plan for Terraform (terraform plan)

The terraform plan command creates an execution plan, which lets you preview the changes that Terraform plans to make to your infrastructure. By default, when Terraform creates a plan it:

  • Reads the current state of any already-existing remote objects to make sure that the Terraform state is up-to-date.
  • Compares the current configuration to the prior state and noting any differences.
  • Proposes a set of change actions that should, if applied, make the remote objects match the configuration. Changes are marked:
    • + create
    • - destroy
    • ~ update in place

Usage: terraform plan [options]

Planning Modes

The following modes are available for both terraform plan and terraform apply:

  • Normal (default) mode changes the remote system to match the changes in the configuration.
  • Destroy mode creates a plan whose goal is to destroy all remote objects that currently exist, leaving an empty Terraform state. Activate destroy mode using the -destroy command line option.
  • Refresh-only mode creates a plan whose goal is only to update the Terraform state and any root module output values to match changes made to remote objects outside of Terraform. Activate refresh-only mode using the -refresh-only command line option.

The planning modes are all mutually-exclusive, so activating any non-default planning mode disables the "normal" planning mode.

Plan Customization Options

In addition to alternate planning modes, there are several options that can modify planning behavior. These options are available for both terraform plan and terraform apply:

  • -destroy - Select the "destroy" planning mode, which creates a plan to destroy all objects currently managed by this Terraform configuration instead of the usual behavior.
  • -refresh-only - 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.
  • -refresh=false - Skip checking for external changes to remote objects while creating the plan. This can make planning faster but risks planning against stale state information.
  • -replace=resource - Force replacement of a particular resource instance using its resource address. If the plan would normally update or skip this instance, Terraform will instead plan to replace it. Can be used multiple times for multiple resources.
  • -target=resource - Limit the planning operation to only the given module, resource, or resource instance and its dependencies. Can be used multiple times. Intended for exceptional use only.
  • -var 'foo=bar' - Set a value for one of the input variables in the root module. Use multiple times to set more than one variable.
  • -var-file=filename - Load variable values from the given file, in addition to the default terraform.tfvars and *.auto.tfvars files. Use multiple times to include more than one variables file.

Other Options

  • -compact-warnings - If Terraform produces any warnings that are not accompanied by errors, shows them in a more compact form with only summary messages.
  • -detailed-exitcode - Return detailed exit codes when the command exits. Exit codes meaning:
     0 - Succeeded, no changes
     1 - Errored
     2 - Succeeded, changes present
  • -input=true - Ask for input for variables if not directly set.
  • -lock=false - Don't hold a state lock during the operation. Dangerous if others might concurrently run commands against the same workspace.
  • -lock-timeout=0s - Duration to retry a state lock.
  • -no-color - If specified, output won't contain any color.
  • -out=path - Write a plan file to the given path. This file can then be used as input to the apply command.
  • -parallelism=n - Limit the number of concurrent operations. Defaults to 10.
  • -state=statefile - A legacy option used for the local backend only. See local backend documentation for details.

terraform plan without the -out=FILE flag will create a speculative plan (i.e., a plan without any intent to actually apply it). Developers can use speculative plans to verify the effect of their configuration changes before submitting them for code review.

Use terraform plan -out=FILE to save the generated plan to a file on disk. The saved plan can be later executed by running the terraform apply FILE command. This two-step workflow is primarily intended for automated deployments.

Related commands:

Use the terraform show FILE command to print out the saved plan.

The terraform refresh [options] command reads the current settings from all managed remote objects and updates the Terraform state to match.

Back to Top

6e. Execute changes to infrastructure with Terraform (terraform apply)

The terraform apply command creates/modifies infrastructure according to Terraform configuration files in the current directory or a given Terraform plan.

Usage: terraform apply [options] [PLAN]

By default (without a plan file), terraform apply will generate a new plan (same as terraform plan) and present it for approval before taking any action. In this scenario terraform apply supports all of terraform plan's planning modes and plan customization options. For more details, see the terraform plan section above.

If a plan file (created earlier with terraform plan -out=FILE) is provided, Terraform will take the actions described in that plan without any confirmation prompt.

Apply Options

  • -auto-approve - Skip interactive approval of plan before applying.
  • -backup=path - Path to backup the existing state file before modifying. Defaults to the -state-out path with .backup extension. Set to "-" to disable backup.
  • -compact-warnings - If Terraform produces any warnings that are not accompanied by errors, show them in a more compact form with only summary messages.
  • -destroy - Destroy Terraform-managed infrastructure. The command terraform destroy is a convenience alias for this option.
  • -lock=false - Don't hold a state lock during the operation. Dangerous if others might concurrently run commands against the same workspace.
  • -lock-timeout=0s - Duration to retry a state lock.
  • -input=true - Ask for input for variables if not directly set.
  • -no-color - If specified, output won't contain any color.
  • -parallelism=n - Limit the number of parallel resource operations. Defaults to 10.
  • -state=path - Path to read and save state (unless -state-out is specified). Defaults to terraform.tfstate.
  • -state-out=path - Path to write state to that is different than -state. Useful to preserve the old state.

Back to Top

6f. Destroy Terraform managed infrastructure (terraform destroy)

The terraform destroy command is a convenient way to destroy all remote objects managed by a particular Terraform configuration.

Usage: terraform destroy [options]

This command is an alias for: terraform apply -destroy. It also accepts many of the plan customization options accepted by the terraform plan command.

You can also use terraform plan -destroy to create a speculative destroy plan, showing the proposed destroy changes.

Back to Top

6g. Apply formatting and style adjustments to a configuration (terraform fmt)

The terraform fmt command automatically reformats all Terraform configuration files according to HashiCorp's recommended style. 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.

Usage: terraform fmt [options] [target...]

By default, terraform fmt scans the current directory for configuration files. The optional target argument could specify a directory, a file, or STDIN ("-").

Options

  • -list=false - Don't list files whose formatting differs (always disabled if using STDIN).
  • -write=false - Don't write to source files (always disabled if using STDIN or -check).
  • -diff - Display diffs of formatting changes.
  • -check - Check if the input is formatted. Exit status will be 0 if all input is properly formatted and non-zero otherwise.
  • -no-color - If specified, output won't contain any color.
  • -recursive - Also process files in subdirectories. By default, only the given directory (or current directory) is processed.

Back to Top

Practice Questions

What is the primary purpose of the terraform init command?
What command should you use to see the execution plan for your configuration?
What is the function of the terraform apply command?
Which Terraform command is used to remove all resources defined in the configuration?
What does the terraform fmt command do?
Which command can be used to check the syntax and validity of Terraform configurations?
What is the primary purpose of the terraform refresh command?
What happens if you run terraform apply without an execution plan?
Which tasks does the terraform init command perform?
What command must be executed the very first time Terraform is run within a new or existing configuration directory?
What types of issues does the terraform validate command check for in a configuration?
After changing the count value in a Terraform configuration, what should be done next to make the infrastructure match the updated configuration?
Why does running terraform apply on a new configuration fail if terraform init hasn't been run first?
When you initialize Terraform, where does it cache modules from the Public Terraform Module Registry?
Which terraform command can be used to produce a human readable summary of a plan file?
Which command is used to force a recreation of a resource in the next apply?
Which command can be used to force a replacement of a resource?
What does the terraform plan -out=tf_plan command do?
Which command will show changes required by the current configuration in a human readable format?
What is the purpose of the terraform plan -destroy command?
What does the terraform init -backend-config option do?
What is the purpose of the terraform apply -auto-approve option?
What is the purpose of the terraform taint command?
Which command can be used to upgrade the provider versions in your terraform configuration?
Which Terraform command is used to format configuration files to a canonical format and style?
What is the default behavior of the terraform apply command when run in an uninitialized directory?
Which Terraform command is used to automatically approve the plan and apply it?
What is the workflow for deploying new infrastructure with Terraform?
You are planning to destroy a temporary environment managed by Terraform. Which command should you use to produce a list of resources that will be deleted before actually performing the destroy operation?

Back to Top