A. Language guide
Definition:
- Docs
- Written in HCL
- Can be written in Json,
.tf.json
- Can be written in 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
- use different variable files for different env:
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:
- Command-line variable: Any
-var
and-var-file
options on the command line in the order provided and variables from HCP Terraform - Variable definition files:
- Any
*.auto.tfvars
or*.auto.tfvars.json
files in lexical order- auto files are always loaded
terraform.tfvars.json
fileterraform.tfvars
file
- Any
- Environment variables: You can set environment variables using the
TF_VAR_
prefix to a variable name (export TF_VAR_instance_type=t3.medium
) - The
default
argument of thevariable
block
- Command-line variable: Any
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 useterraform_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
- https://developer.hashicorp.com/terraform/language/meta-arguments#lifecycle
depends_on
: explicitly set the order in which Terraform creates resources- one module can depends on another module, local,.?
count
for_each
: work with a map or set (no value) to create multiple resource/modulesprovider
: Terraform Providerproviders
: Terraform Providerlifecycle
:- resource can be: created, destroyed, update in-place, destroyed & created
- accepts a rule that customizes how Terraform performs the lifecycle stages for each resource
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:
- Types of named values:
- Terraform Resource:
<RESOURCE TYPE>.<NAME>
- Terraform Variable:
var.<NAME>
- Terraform Local:
local.<NAME>
- Terraform Output:
module.<MODULE NAME>.<OUTPUT NAME>
- Terraform Data Source:
data.<DATA TYPE>.<NAME>
- File system and workspace:
path.module
path.root
path.cwd
terraform.workspace
- Block-local values:
count.index
each.key
/each.value
self
: provisioner block and connection block
- Terraform Resource:
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]
tovar.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
resource
,data
,provider
, andprovisioner
- supported inside
- 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
- Used for Terraform Module, Terraform Provider, terraform block’s
required_version
setting version = "<operator> <version>"
- version = ”>= 1.2.0, < 2.0.0”
- operators:
= , 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
- …