Terraform

From Chorke Wiki
Jump to navigation Jump to search
# wget -qO - terraform.gpg https://apt.releases.hashicorp.com/gpg\
# | sudo gpg --dearmor -o /usr/share/keyrings/terraform-archive-keyring.gpg
#
# sudo echo "deb [arch=$(dpkg --print-architecture)\
#  signed-by=/usr/share/keyrings/terraform-archive-keyring.gpg]\
# https://apt.releases.hashicorp.com $(lsb_release -cs) main" > /etc/apt/sources.list.d/terraform.list

curl -fsSL https://apt.releases.hashicorp.com/gpg\
| sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg

cat << EOF | sudo tee /etc/apt/sources.list.d/hashicorp.list >/dev/null
deb [arch=$(dpkg --print-architecture)\
 signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg]\
 https://apt.releases.hashicorp.com $(lsb_release -cs) main
EOF

sudo apt update  && sudo apt list  --upgradeable
sudo apt upgrade && sudo apt install terraform
terraform version

Structure

sdlc/
├─ main.tf              # Main Terraform config file
├─ variables.tf         # Variable declarations
├─ terraform.tfvars     # Variable assigned
├─ outputs.tf           # Output definitions
├─ provider.tf          # Provider-specific config
├─ terraform.tfstate    # Terraform state file
├─ dev.tf               # Dev  Env config for development
├─ prod.tf              # Prod Env config for production
├─ modules/             # Directory for custom modules
│  ├─ module1/          # Custom module 1
│  │  ├─ main.tf        # Module-specific Terraform config
│  │  ├─ variables.tf   # Module-specific variables
│  │  └─ outputs.tf     # Module-specific outputs
│  └─ module2/          # Custom module 2
│     ├─ main.tf
│     ├─ variables.tf
│     └─ outputs.tf
├─ environments/        # Directory for env
│  ├─ dev/              # Development env
│  │  ├─ main.tf        # Env specific Terraform config
│  │  ├─ variables.tf
│  │  └─ outputs.tf
│  └─ prod/             # Production env
│     ├─ main.tf
│     ├─ variables.tf
│     └─ outputs.tf
├─ scripts/             # Scripts or utility for IaC
└── README.md

Summary

  • A collection of *.tf files in a single directory is a module
  • If those *.tf files exist in the root level directory of a stack (ie, where you cd to in order to run terraform), then you have the option of creating terraform.tfvars, rather than always editing values into variables.tf
  • If those *.tf files exist in a module other than the root level directory, you do not have the option of using terraform.tfvars in that directory
  • terraform.tfvars should be considered your way of setting variables for your deployment; if you're still editing variables.tf for every one of your unique deployments, then your stack still needs work before you can consider it ready to be shared with others

Playground

terraform init
terraform plan
terraform apply
terraform destroy

References