Terraform
Terraform is an infrastructure-as-code (IaC) software tool created by HashiCorp.
Index
Install
HashiCorp distributes Terraform as a binary package.
- Go to the Downloads page.
- Download the precompiled binary.
- Add the precompiled binary to the PATH.
Usage
Check version.
terraform version
Initialize a working directory.
terraform init
Download and update modules mentioned in the root module.
terraform get
Rewrite configuration files to a canonical format and style.
terraform fmt
terraform fmt -recursive
Validate the configuration files without accessing any remote service.
terraform validate
Create an execution plan to preview changes in the infrastructure.
terraform plan
Execute the actions proposed in a plan.
terraform apply
Destroy all remote resources of a plan.
terraform destroy
Modules
A module is a container for multiple resources that are used together.
Configuration with multiple providers and modules.
root
├── main.tf
├── modules.tf
├── submodule1
│ ├── main.tf
│ ├── modules.tf
│ ├── submodule2
| | ├── main.tf
| | └── ...
│ ├── submodule3
| | ├── main.tf
| | └── ...
│ └── ...
└── ...
At root
module, main.tf
file.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
provider "aws" {
alias = "prov1"
# ...
}
provider "aws" {
alias = "prov2"
# ...
}
At root
module, modules.tf
file.
module "submodule1" {
source = "./submodule1"
providers = {
aws.prov1 = aws.prov1
aws.prov2 = aws.prov2
}
}
At submodule1
module, main.tf
file.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
configuration_aliases = [
aws.prov1,
aws.prov2,
]
}
}
}
At submodule1
module, modules.tf
file.
module "submodule2" {
source = "./submodule2"
providers = {
aws = aws.prov1
}
}
module "submodule3" {
source = "./submodule3"
providers = {
aws = aws.prov2
}
}
At submodule2
and submodule3
modules, main.tf
file.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}