Definition:

  • Docs
  • Written in HashiCorp Config Language, HCL
  • Can be repeated
  • Resources are infrastructure objects such as compute engine, storage, containers, et cetera.

1. Overview:

2. Override files:

  • Merging

3. Dependency lock file:

4. Test files:

2. For .tf

  • Argument:
    • Assign a value/attribute to a name
      • image_id = "abc123"
    • Context where the argument appears determines what value types are valid
      • for example, each resource type has a schema that defines the types of its arguments
      • can be an expression
  • Block: ^1945db
    • Containers for other content
    • Has a block type
      • The type defines how many labels must present after type
        • can be 0 labels
      •     <type> "<label1>" ["<label2>",...]{
            }
    • Has block body within {}
      • can have nested block
      •     resource "google_compute_instance" "vm_instance" {
            name         = "terraform-instance"
            machine_type = "e2-micro"
          
            boot_disk {
          	initialize_params {
          	  image = "debian-cloud/debian-11"
          	}
            }
  • Identifier: ^612f22
    • Argument, block type names, and the names of most Terraform-specific constructs like resources, input variables, etc. are all identifiers.
    • Can contain letters, digits, underscores (_), and hyphens (-).
    • The first character can not be a digit.
  • Comment:
    • # or // for a single-line
    • /* to */ for block

3. For .tf.json:

4. Style conventions:

  • run terraform fmt

  • Indent 2 spaces

  • Align at equal sign

    ```hcl
    ami           = "abc123"
    instance_type = "t2.micro"
      ```
    
  • Each resource block describes one or more infrastructure objects

2. Resource block:

  • Syntax of a block
  • Resource types:
    • Provider
      • A plugin that offers a collection of resource types in modules.
      • Each resource type is implemented by a provider.
      • Based on the resource type’s name, Terraform can usually determine which provider to use
    • Within the block, resource arguments assign value to the object’s attributes
  • Meta-arguments
  • Custom condition checks
  • Operation timeouts:
    • Some resource types provide a special timeouts nested block
    • Allows to customize how long certain operations are allowed to take before consideredfailed

3. Resource behaviour

  • Identifier for that real infrastructire object is saved in Terraform’s state
  • Applying a Terraform configuration will:
    • Create resources that exist in the configuration but are not associated with a real infrastructure object in the state.
    • Destroy resources that exist in the state but no longer exist in the configuration.
    • Update in-place resources whose arguments have changed.
    • Destroy and re-create resources whose arguments have changed but which cannot be updated in-place due to remote API limitations.
  • Accessing resource attributes:
    • Expressions can be used to access information about resources in the same module
    • Data sources are special type of resource used only for looking up information
  • Resource dependencies:
    • Some resources must be processed after other specific resources
      • because infrastructure need
      • or requires infor generated by another resource
    • Terraform analyzes the expressions and order them
    • If there is implicit dependencies, depends on can be explicitlty specified
  • Local-only resources:
    • local-only resource types exist for
      • generating private keys,
      • issuing self-signed TLS certificates,
      • and even generating random ids.
    • The behavior is the same as all other resources, but their result data exists only within the Terraform state.
    • ”Destroying” such a resource means only to remove it from the state, discarding its data.

4. Meta-arguments

  • depends on

  • count

  • for each

  • provider

  • lifecycle

  • provisioner

  • s

1.

  • Terraform relies on plugins called providers to interact with cloud providers, SaaS providers, and other APIs.
  • Terraform configurations must declare which providers they require so that Terraform can install and use them.
    • Additionally, some providers require configuration (like endpoint URLs or cloud regions) before they can be used.

2. Provider configuration:

3. Provider requirements:

4. Dependency lock file:

1.

2. Input variables:

    • To customize aspects of Terraform modules without altering the module’s own source code
    • To share modules across different Terraform configurations, making your module composable and reusable.
    • Like a function argument
  • Declaring an Input Variable

    ```hcl
      variable "image_id" {
        type = string
      }
      
      variable "availability_zone_names" {
        type    = list(string)
        default = ["us-west-1a"]
      }
      
      variable "docker_ports" {
        type = list(object({
          internal = number
          external = number
          protocol = string
        }))
        default = [
          {
            internal = 8300
            external = 8300
            protocol = "tcp"
          }
        ]
      }
      ```
    
    • Some names are reserved: sourceversionproviderscountfor_eachlifecycledepends_onlocals
  • Arguments:
    • default
      • A default value which then makes the variable optional.
      • considered to be optional and the default value will be used if no value is set when calling the module or running Terraform
    • type
      • Restrict the types of value for the variable
      • With type keyword, it can be:
        • string
        • number
        • bool
      • Can use type constructors:
        • list(<TYPE>)
        • set(<TYPE>)
        • map(<TYPE>)
        • object({<ATTR NAME> = <TYPE>, ... })
        • tuple([<TYPE>, ...])
    • description
      • This specifies the input variable’s documentation.
    • validation
      • A block to define validation rules, usually in addition to type constraints.
      •   variable "image_id" {
          		  type        = string
          		  description = "The id of the machine image"
         
          		  validation {
          		    condition     = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
          		    error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
          		  }
          		}
    • sensitive
      • Prevents Terraform from showing its value in the plan or apply output, when you use that variable elsewhere in your configuration.
      • sensitive = true
    • nullable
      • Specify if the variable can be null within the module.
  • Using Input Variable Values:
    • Must prefix with var
    • var.<NAME>, where <NAME> matches the label given in the declaration block:
    • resource "aws_instance" "example" {
          instance_type = "t2.micro"
          ami           = var.image_id
        }
  • Assigning Values to Root Module Variables:
    • s.
    • Variables on the command line
    • Variable Definitions (.tfvars) Files

3. Output variables:

  • Make information about infrastructure available on the command line when run terraform apply
  • Can expose information for other Terraform configurations to use.
  • Similar to return values in programming languages.
  • Declaring an Output Value:

    ```hcl
    output "<identifier>" {
        value = aws_instance.server.private_ip
      }
      ```
    
    • Identifer
      • In a root module, this name is displayed to the user
      • In a child module, it can be used to access the output’s value.
    • Must have a value
  • Accessing Child Module Outputs:
    • In a parent module, outputs of child modules are available in expressions as module.<MODULE NAME>.<OUTPUT NAME>
    • prefix module
  • Custom condition checks:

1. Overview:

  • A module:
    • A container for multiple resources that are used together
    • A collections of .tf and/or .tf.json in a directory
      • Each must defines a distinct set of config objects
      • Not in nested directory
  • The root module:
    • A Terraform config has atleast 1 module which is the root module
    • Contains all .tf files in the working directory
  • Child module:
    • A Terraform module can call other modules to include their resources in the configuration
  • Published modules:
    • Terraform can load modules from public (Terraform Registry) or private registry
  • Using modules:
  • Developing modules

2. Module block:

  • Calling a child module:
    • To cal a module means to include the contents of that module into the configuration with specific values for its Input variables
    • module "<local-name>>" {
          source = "./app-cluster"
        
          <input-variable-defined-by-the-module> = 5
        }
    • This block is called the calling module of the child module
      • The label right after is the local-name
    • Module call use arguments:

3. Module sources:

4. Module meta-arguments:

  • s

5. Module development:

  • Expressions:

    • Represent a value, either literally or by referencing and combining other values. They appear as values for arguments, or within other expressions.

2. Types and values

  • Types:

7. Conditional expressions

  • Custom
  • Preconditions and Postconditions

13. Version constraints:

  • s

1.

2. Terraform Cloud

3. Terraform Backend