Terraform-Associate-Notes

HashiCorp Certified: Terraform Associate (003) Notes

This repository contains notes for the HashiCorp Certified: Terraform Associate (003) exam. The notes are based on the official study guide provided by HashiCorp.

For the exam objectives and general information go here

Table of Contents

  1. Infrastructure as Code (IaC)
  2. Terraform Workflow
  3. Terraform Commands
    1. Terraform Init
    2. Terraform Plan
    3. Terraform Apply
    4. Terraform Destroy
  4. Installing Terraform
  5. Common Terraform Blocks
    1. Terraform Providers
    2. Terraform Resources
    3. Terraform Data
  6. Terraform State
    1. Local State Storage
    2. Remote State Storage
    3. Terraform State Commands
  7. Variables
    1. Base Types
    2. Complex Types
  8. Outputs
  9. Terraform Provisioners
  10. Terraform Modules
  11. Terraform Built-in Functions
  12. Type Constraints - Terraform Variables
  13. Dynamic Blocks
  14. Additional Terraform Commands
  15. Terraform CLI Utilities
    1. Terraform fmt
    2. Terraform apply -replace
    3. Terraform import
  16. Terraform Configuration Block
  17. Terraform Workspaces
  18. Debugging Terraform
  19. Terraform Cloud and Enterprise Offerings
    1. Hashicorp Sentinel
    2. Terraform Vault
    3. Terraform Registry
    4. Terraform Cloud Workspaces
    5. Terraform OSS Workspaces
    6. Benefits of Terraform Cloud
  20. Benefits of Terraform Cloud

Infrastructure as Code (IaC)

Terraform Workflow

  1. Write Your Terraform Code

    • Start by creating a GitHub repo as a common best practice.
  2. Review

    • Continually add and review changes to the code in your project.
  3. Deploy

    • After one last review/plan, you’ll be ready to provision real infrastructure.

Terraform Commands

Terraform Init

Terraform Plan

Terraform Apply

Terraform Destroy

Installing Terraform

  1. Method 1: Download, Unzip, Use

    • Download the zipped binary from the HashiCorp website.
    • Unzip the Terraform binary.
    • Place it in your system’s $PATH as a best practice.
  2. Method 2: Set Up Terraform Repository on Linux

    • Set up a HashiCorp Terraform repository on Linux (Debian, RHEL, Amazon Linux).
    • Use a package manager to install Terraform.
    • The package manager installs and sets it up for immediate use.

Terraform Blocks

Terraform Providers

Terraform Resources

resource "<PROVIDER>_<RESOURCE_TYPE>" "<NAME>" {
  # Configuration arguments
}

Terraform Data

data "<PROVIDER>_<DATA_SOURCE_TYPE>" "<NAME>" {
  # Configuration arguments
}

Addressing Provider, Data, and Resource Blocks

Block Type Addressing Format
Provider provider.<provider_name>
Data data.<data_source_type>.<name>
Resource resource.<resource_type>.<name>

Terraform State

Local State Storage

Remote State Storage

Terraform State Commands

These commands are used to manipulate and interact with the Terraform state file directly.

Command Description Use Case
terraform state show Displays detailed state information for a given resource Useful for inspecting current state of a specific resource
terraform state rm Removes a specified resource from the state file Use when a resource needs to be unmanaged by Terraform
terraform state list Lists all resources currently tracked in the state Helpful for viewing all managed resources
terraform state mv Moves a resource from one state to another Used for refactoring or re-structuring Terraform configuration
terraform state pull Retrieves the state file from its remote storage location Use to download and view the current remote state
terraform state push Uploads a local state file to the configured remote state location Used to manually synchronize the local state with remote state
terraform state replace-provider Replaces provider references in the state file Useful when changing providers or their versions
terraform state show Shows attributes of a single resource in the state Inspect detailed information about a specific resource

Variables

Base Types

Sensitive Variables

variable "db_password" {
  description = "The password for the database"
  type        = string
  sensitive   = true
}

Variable Validation

variable "port" {
  description = "The port on which the application runs"
  type        = number

  validation {
    condition     = var.port >= 1 && var.port <= 65535
    error_message = "The port number must be between 1 and 65535."
  }
}

Complex Types

Type Description Example
String Represents text "example string"
Number Represents numerical values 42
Bool Represents true or false values true
List An ordered sequence of values ["item1", "item2"]
Map A collection of key-value pairs {"key1" = "value1"}
Set A collection of unique values set("item1", "item2")
Object A collection of named attributes object({name=string})
Tuple A sequence of values of different types tuple([string, number])

Outputs

Terraform Provisioners

Remote Execution Provisioners

Example:

resource "aws_instance" "example" {
  # resource configuration
  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx"
    ]
  }
}

Local Exec Provisioners

Example:

resource "aws_instance" "example" {
  # resource configuration
  provisioner "local-exec" {
    command = "echo 'Hello, World!'"
  }
}

Terraform Modules

Accessing Terraform Modules

Using Terraform Modules

Declaring Modules in Code

Terraform Module Outputs

Terraform Built-in Functions

Examples of Terraform built-in functions:

Function Description
abs Returns the absolute value of a number.
ceil Rounds a number up to the nearest whole number.
floor Rounds a number down to the nearest whole number.
max Returns the maximum value from a list of numbers.
min Returns the minimum value from a list of numbers.
concat Concatenates multiple strings together.
element Returns the element at a specific index in a list.
length Returns the length of a string or list.
lower Converts a string to lowercase.
upper Converts a string to uppercase.
replace Replaces occurrences of a substring in a string.
split Splits a string into a list of substrings based on a delimiter.
join Joins a list of strings into a single string using a delimiter.
format Formats a string using placeholders and values.
jsonencode Converts a value to its JSON representation.
jsondecode Converts a JSON string to its corresponding value.

Type Constraints

Primitive Types

Complex Types

Dynamic Blocks

Additional Terraform Commands

Terraform fmt

Terraform apply -replace

previously known as taint and untaint commands before Terraform v0.12

Terraform import

Terraform validate

Terraform show

Terraform graph

Example output: graph

Terraform output

Terraform refresh

Terraform console

Terraform Configuration Block

Terraform Workspaces

Command Description
terraform workspace list Lists all the workspaces in the current working directory. Displays an asterisk (*) next to the current workspace.
terraform workspace show Shows the name of the current workspace.
terraform workspace new <name> Creates a new workspace with the specified name. This also switches to the newly created workspace.
terraform workspace select <name> Switches to the specified workspace. If the workspace does not exist, it will return an error.
terraform workspace delete <name> Deletes the specified workspace. The workspace must not be currently selected, and it must be empty (no managed resources).
terraform workspace select default Switches back to the default workspace.

Debugging Terraform

Terraform Cloud and Enterprise Offerings

Hashicorp Sentinel

Use Cases for Sentinel

HasiCorp Vault

Terraform Registry

Terraform Cloud Workspaces

Terraform Cloud Folder

Terraform OSS Workspaces

Benefits of Terraform Cloud

Feature HashiCorp Cloud Platform (HCP) Local State External State
Storage Location Managed by HashiCorp in the cloud Stored on local disk of the user’s machine Stored in remote services (e.g., AWS S3, Azure Blob Storage)
Access Control Built-in authentication and RBAC (Role-Based Access Control) Access controlled by file system permissions Access control managed by the external service (e.g., IAM policies for S3)
Collaboration Native support for team collaboration with shared state and locking Limited, as only the local user can modify the state Supports collaboration through state locking and shared access via remote storage
State Locking Automatic state locking to prevent conflicts No built-in locking; risk of state corruption with concurrent use Supports state locking using a service like DynamoDB (with S3 backend)
Security Secure storage with encryption and automated backups Relies on local machine’s security; encryption is manual Security features depend on the remote service (e.g., server-side encryption for S3)
Backup and Recovery Automatic state versioning and backups Manual backups required Automatic backups and versioning can be configured (e.g., S3 versioning)
Scalability Highly scalable, managed by HashiCorp Limited by local machine’s storage capacity and performance Scalable based on the chosen external storage solution
Ease of Setup Simple setup with Terraform Cloud integration Very easy, no setup needed for local use Requires configuration of backend and authentication
Cost Subscription-based pricing model for HCP No cost beyond local storage Cost depends on the external storage service (e.g., AWS S3 storage fees)
Compliance and Governance Built-in compliance tools like Sentinel for policy enforcement No built-in compliance tools Compliance depends on the external service; may require custom solutions