Skip to main content
  1. 🔰Posts/
  2. 🗂️My Trainings/
  3. Terraform Trainings and Certifications/
  4. Terraform on AWS with SRE & IaC DevOps/

Terraform: Basics

·1617 words·8 mins

Prerequisite #

  • Install Terraform CLI
  • Install AWS CLI
  • Install VS Code Editor
  • Install HashiCorp Terraform plugin for VS Code

Terraform basic commands #

  • terraform init
    • used to initialize a working directory that contains terraform config files
    • this is the first command that should be run after writing new terraform configuration
    • it will download the provider plugins
    • .terraform.lock.hcl file is created to record the provider selections. Include this file in your version control repository so that Terraform can guarantee to make the same selections by default when you run terraform init in the future.
    • terraform init -upgrade - command to upgrade the provider in Terraform. This command will initialize the working directory and upgrade the provider to the latest version available, including any additional functionality that may have been added. If Terraform was already initiated and providers were downloaded, Terraform will not upgrade to the new version by default.
  • terraform validate
    • validates syntax and consistency of the terraform files
  • terraform plan
    • creates an execution plan
    • terraform performs a refresh and determines what actions are necessary to achieve the desired state specified in the configuration files
  • terraform apply
    • will apply the changes required to be in line with the desired state
    • by default, apply will scan the current directory and apply it’s configuration (provision the infrastructure)
    • terraform apply -refresh-only - detect drift between the Terraform configuration and the actual state of the resources in the cloud provider. It will update the state file with any changes made outside of Terraform, ensuring that the configuration remains in sync with the actual resources.
    • terraform apply -replace=<resource> - allows you to tag the specific resource for replacement without impacting the rest of the managed infrastructure. This ensures that only the tagged resource is recreated, potentially resolving any issues with the local script execution.
  • terraform destroy
    • will destroy the terraform-managed infrastructure
    • terraform destroy -target <virtual machine> - destroy only the target resource.

Other useful commands #

  • terraform fmt - HashiCorp recommends using consistent formatting in all config files by using the terraform fmt command. Optional command, helps with formatting
  • terraform state command can be used to check what resources have been deployed against the terraform state file
    • list - list resources in the state
    • show - show a resource in the state
    • terraform state rm - will remove the specified resource from the Terraform state, allowing you to then run terraform destroy to remove all remaining resources except for the resource that was removed from the state. This approach effectively excludes the specified resource from the destruction process.

The terraform state command and its subcommands can be used for various tasks related to the Terraform state. Some of the tasks that can be performed using the terraform state command are:

  1. Inspecting the Terraform state: The terraform state show subcommand can be used to display the current state of a Terraform configuration. This can be useful for verifying the current state of resources managed by Terraform.

  2. Updating the Terraform state: The terraform state mv and terraform state rm subcommands can be used to move and remove resources from the Terraform state, respectively.

    Example: terraform state mv aws_s3_bucket.data-bucket aws_s3_bucket.data-bucket-prod

  3. Pulling and pushing the Terraform state: The terraform state pull and terraform state push subcommands can be used to retrieve and upload the Terraform state from and to a remote backend, respectively. This is useful when multiple users or systems are working with the same Terraform configuration.

  4. Importing resources into Terraform: The terraform state import subcommand can be used to import existing resources into the Terraform state. This allows Terraform to manage resources that were created outside of Terraform.

By using the terraform state command and its subcommands, users can manage and manipulate the Terraform state in various ways, helping to ensure that their Terraform configurations are in the desired state.

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

https://developer.hashicorp.com/terraform/cli/state

More info: Terraform State

  • terraform workspace
    • delete - Delete a workspace
    • list - List Workspaces
    • new - Create a new workspace
    • select - Select a workspace
    • show - Show the name of the current workspace
Terraform workspaces are a feature that allow you to manage multiple instances of your infrastructure using the same configuration files, each with its own isolated state file. This helps in organizing different environments, such as development and production, without interfering with each other.
  • terraform show - Display the current state of the resources being managed by Terraform. It provides detailed information about the infrastructure that Terraform is managing, including resource attributes, dependencies, and configuration.
  • terraform output - Reads an output variable from a Terraform state file and prints the value.
  • terraform refresh - Update the state file of your infrastructure with metadata that matches the physical resources they are tracking

The difference between terraform refresh and terraform apply -refresh-only:

terraform refresh updates the state file to match real infrastructure but does not produce or apply a plan, while terraform apply -refresh-only runs through the full plan/apply workflow but only refreshes the state (no resource changes), making it auditable and consistent with Terraform’s apply process.

terraform refresh is being considered a legacy command. Newer workflows encourage apply -refresh-only.

  • terraform providers- Prints out a tree of modules in the referenced configuration annotated with their provider requirements

It is said that best terraform practice is to output the terraform plan to a file and then run terraform apply with the file input.

terraform plan -out tf.plan

terraform apply tf.plan

*terraform will not ask for confirmation (just like using it with the -auto-approve option) when executing the plan from the file.

The terraform state file is the only way Terraform can track which resources it is managing. It often contains sensitive information so must be stored securely and access must be restricted.

  • terraform graph - used to generate a visual representation of either a configuration or execution plan. The output is in the DOT format, which can be used by GraphViz to generate charts.
    • terraform graph -type=plan | dot -Tpng >graph.png

More info: https://developer.hashicorp.com/terraform/cli/commands/graph

Terraform Configuration Syntax #

Source: Terraform Language Syntax

Terraform Blocks #

Code in Terraform language is stored in plain text files ended with the .tf extension. Those are called Terraform Configuration Files or Terraform Manifests.

2 types of blocks:

  • Top Level
    • resource
    • provider
  • Block inside Block
    • provisioners
    • resource-specific block tags

Terraform Arguments, Attributes and Meta-Arguments #

  • Terraform Arguments are the Input Values.
  • Terraform Attributes are the Output Values.
  • Arguments can be required or optional.
resource "aws_instance" "ec2" {
  ami           = "ami-08f714c552929eda9"
  instance_type = "t2.nano"  
}
  • Attributes are values exposed by a particular resource. It’s format looks like:
    resource_type.resource_name.attribute_name

  • Meta-Arguments change a resource type’s behavior

    • count
    • depends_on
    • for_each
    • lifecycle
    • provider
aws_instance resource documentation: https://registry.terraform.io/providers/-/aws/latest/docs/resources/instance contains references to all Arguments and Attributes.

More info:

Top-Level Blocks #

  • Terraform Settings Block
  • Provider Block
  • Resource Block
  • Input Variables Block
  • Output Values Block
  • Local Values Block
  • Data Sources Block
  • Modules Block

Terraform Blocks: https://github.com/stacksimplify/hashicorp-certified-terraform-associate/tree/main/03-Terraform-Fundamental-Blocks

Terraform Resources: https://github.com/stacksimplify/hashicorp-certified-terraform-associate/tree/main/04-Terraform-Resources

Terraform Comments #

3 ways to make comments in Terraform:

  • Single-line:
    • #
    • //
  • Multi-line:
/*
Multi-line comments
Line 1
Line 2
*/

Terraform Modules #

Terraform Modules are containers for multiple resources that are used together. A module consists of a collection of .tf files kept together in a directory.
  • Modules are the main way of packaging and reusing resource configurations in Terraform
  • Every Terraform configuration has at least one module, known as it’s root module, which consists of the resources defined in the .tf files placed in the main working directory
  • A Terraform module (usually the root module of a configuration) can call other modules to include their resources into the configuration
  • A module that has been called by another module is often referred to as a child module
    • Child modules can be called multiple times within the same configuration and multiple configurations can use the same child module
  • In addition to modules from the local system, Terraform can load modules from a public or private registry
    • It is therefore possible to publish modules for others to use and to use modules published by others

Version Constraints #

Source:

Use the following syntax to specify version constraints:

version = "<operator> <version>"

In the following example, Terraform installs a versions 1.2.0 and newer, as well as version older than 2.0.0:

version = ">= 1.2.0, < 2.0.0"

Operators #

The following table describes the operators you can use to configure version constraints:

OperatorDescription
=,
no operator
Allows only one exact version number. Cannot be combined with other conditions.
!=Excludes an exact version number.
>,
>=,
<,
<=
Compares to a specified version. Terraform allows versions that resolve to true. The > and >= operators request newer versions. The < and <= operators request older versions.
~>Allows only the right-most version component to increment. Examples:

- ~> 1.0.4: Allows Terraform to install 1.0.5 and 1.0.10 but not 1.1.0.
- ~> 1.1: Allows Terraform to install 1.2 and 1.10 but not 2.0.
It is a Best Practice to use an exact version when using modules from the Terraform registry since they can change significantly between versions and cause issues.

» Sources « #

Kalyan’s GitHub Repositories:

Additional resources:

» References « #

» Disclaimer « #

This series draws heavily from Kalyan Reddy Daida’s Terraform on AWS with SRE & IaC DevOps course on Udemy.

His content was a game-changer in helping me understand Terraform.

About the instructor
🌐 Website📺 YouTube
💼 LinkedIn🗃️ GitHub

ℹ️Shared for educational purposes only, no rights reserved.

RobK
Author
RobK
DevOps | Agile | AWS | Ansible | Terraform | PowerShell | Windows | Linux | Git