A. Language guide

Definition:

  • Docs
  • Written in HCL
    • Can be written in Json, .tf.json
  • Resources are infrastructure objects such as compute engine, storage, containers, et cetera.
  • Setting block is terraform block
  • Tips:
    • use different variable files for different env: dev.tfvars

1. Style guide

2. Syntax

3. Files & Config structures

4. Install Terraform Provider

Provider Requirements:

5. Create and manage resources

6. Set configuration parameters

  • Define module input arguments with Terraform Variable
    • Once you assign a value to a variable, you cannot reassign that variable within the same file
    • Assign values to input variables

    • Terraform uses the following order of precedence:
      1. Command-line variable: Any -var and -var-file options on the command line in the order provided and variables from HCP Terraform
      2. Variable definition files:
        1. Any *.auto.tfvars or *.auto.tfvars.json files in lexical order
          • auto files are always loaded
        2. terraform.tfvars.json file
        3. terraform.tfvars file
      3. Environment variables: You can set environment variables using the TF_VAR_ prefix to a variable name (export TF_VAR_instance_type=t3.medium)
      4. The default argument of the variable block

8. Query infrastructure data:

9. Build and use modules

Terraform Module

10. Manage Terraform State

11. Store Terraform State remotely

15. Use Terraform Provisioner:

Run provisioner without a resource:
  • before v1.4, it is null_resource, recommended to use terraform_data
Use a provisioner:

B. Reference

1. Configuration blocks:

data block
locals block
module block
moved block
output block
provider block
terraform block:
  • Setting block
  •   terraform {
        required_version = "<version>"
        required_providers {
          <PROVIDER> {
            version = "<version-constraint>"
            source = "<provider-address>"
          }
        }
        provider_meta "<LABEL>" { 
          # Shown for completeness but only used for specific cases     
        }
        backend "<TYPE>" {        
          # `backend` is mutually exclusive with `cloud` 
          "<ARGUMENTS>"
        }
        cloud {                   
          # `cloud` is mutually exclusive with `backend` 
          organization = "<organization-name>"
          workspaces {
            tags = [ "<tag>" ]
            name = "<workspace-name>"
            project = "<project-name>"
          }
          hostname = "app.terraform.io"
          token - "<TOKEN>"
        }
        experiments = [ "<feature-name>" ]
      }
variable block

3. Meta-arguments

4. Built-in resources:

terraform_data resource
terraform_remote_state

5. Expressions

Types and values:
  • types:
    • string
    • number
    • bool
    • list
      • every elements must have same values
    • set
    • map
    • null: if set to null, then it will use Terraform Variable’s default value
String and template
  • multiline string
  • string directive
  • whitespace stripping
References to values:
Operators
For expression:
  • different from for_each which used at resource block level
  • for list, set, tuple, map, an object
  • Can be used to create a list, map, filtering
Splat expression:
  • Quicker way of writing For expression
  • [for o in var.list : o.id] to var.list[*].id
  • apply only to lists, sets, and tuples
  • Single Values as Lists
    • If the value is anything other than a null value then the splat expression will transform it into a single-element tuple value
    • If the value is null then the splat expression will return an empty tuple.
    • useful for modules that accept optional input variables whose default value is null to represent the absence of any value
Dynamic block
  • Used inside top-level blocks
    • supported inside resourcedataprovider, and provisioner
  • like a For expression, but produces nested blocks instead of a complex typed value. It iterates over a given complex value, and generates a nested block for each element of that complex value.
    • for_each produces multiple resources
  • Allows nested dynamic blocks
  • With dynamic:
    •     resource "aws_elastic_beanstalk_environment" "tfenvtest" {
        	  name                = "tf-test-name"
        	
        	  dynamic "setting" {
        	    for_each = var.settings
        	    content {
        	      namespace = setting.value["namespace"]
        	      name = setting.value["name"]
        	      value = setting.value["value"]
        	    }
        	  }
        	}
  • Without:
    • 	  resource "aws_elastic_beanstalk_environment" "tfenvtest" {
      		  name                = "tf-test-name"
      		
      		  setting {
      		    namespace = "namespace1"
      		    name = "name1"
      		    value = "value1"
      		  }
      		  setting {
      		    namespace = "namespace2"
      		    name = "name2"
      		    value = "value2"
      		  }
      		}
Type constrants
Version constrants
=
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.

6. Functions:

Numeric
  • abs
  • ceil
  • floor
  • log
  • max
  • min
  • parseint
  • pow
  • signum
String
  • chomp
  • endswith
  • format
  • formatlist
  • indent
  • join
  • lower
  • regex
  • regexall
  • replace
  • split
  • startswith
  • strcontains
  • strrev
  • substr
  • templatestring
  • title
  • trim
  • trimprefix
  • trimsurffix
  • trimspace
  • upper
Collection
  • alltrue
  • anytrue
  • chunklist
  • coalesce
  • coalescelist
  • compact
  • concat
  • contains
  • distinct
  • element
  • flatten
  • index
  • keys
  • length
  • list
  • lookup
Encoding
Filesystem
date and time
hash and crypto
IP network
type conversion
terraform-specific