Terraform
Commands
terraform init
downloads and installs configured providers to
.terraform
folder
terraform fmt
format configuration
terraform validate
check config is syntactically valid and internally consistent
terraform apply
data is written to
terraform.tfstate
terraform show
prints out state with all values
terraform plan
Generates and shows what will change when you run
terraform refresh
updates the local state file against real resources
ensures Terraform has an accurate view of what is in the current environment
terraform state list
advanced state management
terraform destroy
terraform graph > graph.dot
to check and later visualise dependencies between resources
terraform output
output values (only applicable while having an active state
Hashicorp Configuration Language (HCL)
Convention:
main.tf
all resources are declared
# optional section but highly recommended terraform { required_version = ">0.12.0" }
provider "aws" { version = "~> 2.0" region = "us-east-1" }
resource "aws_s3_bucket" "bucket1" { # it does not mean that the resource will be named bucket1 in aws # it is just for the reference in your .tf files } # Objects NOT managed by Terraform data "aws_availability_zones" "available" { state = "available" }
outputs.tf
outputs are declared
variables.tf
variables are declared
Variables
through command line
through file
through env variable
tf_
variable "the_name" {
description = "some description"
type = "string"
default = "var_ExampleAppServerInstance"
}
resource "aws_s3_bucket" "bucket5" {
bucket = var.the_name # this is how you reference the variable
}
Locals
Local values allow you to assign a name to an expression, locals can make your code more readable
locals {
aws_account = "${data.aws_caller_identity.current.account_id}-${lower(somevalue)}"
}
resource "aws_s3_bucket" "bucket5" {
bucket = "${local.aws_account}-bucket6"
}
Output
output "instance_id" {
description = "ID of the EC2 instance"
value = aws_instance.app_server.id
}
output "instance_public_ip" {
description = "Public IP address of the EC2 instance"
value = aws_instance.app_server.public_ip
}
Terraform output values allow you to export structured data about your resources. You can use this data to configure other parts of your infrastructure with automation tools, or as a data source for another Terraform workspace. Outputs are also necessary to share data from a child module to your root module.
terraform{} block
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.27"
}
}
required_version = ">= 0.14.9"
}
for each provider
source
attribute defines an optional hostname, a namespace, and the provider type. Terraform installs providers from the Terraform Registry by defaultMore about
provider
section is HERE
provider{} block
provider "aws" {
shared_credentials_file = "/Users/[your_user]/.aws/credentials"
profile = "private_experiment"
region = "eu-central-1"
}
A provider is a plugin that Terraform uses to create and manage your resources
You can use multiple provider blocks in your Terraform configuration to manage resources from different providers. You can even use different providers together. For example, you could pass the IP address of your AWS EC2 instance to a monitoring resource from DataDog.
resource{} block
resource_type resource_name
| |
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
}
# aws_instance - (resource_type) - a prefix matches a provider name
# aws_instance.app_server - this is a unique resource ID
# ami is region specific, pay attention to it!
More on resource documentation is HERE
Modules
Why?:
Organize configuration
Encapsulate configuration
Re-use configuration
Provide consistency and ensure best practices
What is it?
A Terraform module is a set of Terraform configuration files in a single directory. Even a simple configuration consisting of a single directory with one or more .tf
files is a module. When you run Terraform commands directly from such a directory, it is considered the root module. So in this sense, every Terraform configuration is part of a module. You may have a simple set of Terraform configuration files such as:
.
├── LICENSE
├── README.md
├── main.tf
├── variables.tf
├── outputs.tf
In this case, when you run terraform commands from within the minimal-module
directory, the contents of that directory are considered the root module.
Calling modules
Terraform commands will only directly use the configuration files in one directory, which is usually the current working directory. However, your configuration can use module blocks to call modules in other directories. When Terraform encounters a module block, it loads and processes that module's configuration files.
A module that is called by another configuration is sometimes referred to as a "child module" of that configuration.
Local and remote modules
Modules can either be loaded from the local filesystem, or a remote source. Terraform supports a variety of remote sources, including the Terraform Registry, most version control systems, HTTP URLs, and Terraform Cloud or Terraform Enterprise private module registries.
Example:
Code from tutorial:
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
provider "aws" {
region = "us-west-2"
}
# defines a Virtual Private Cloud (VPC), which will provide
# networking services for the rest of your infrastructure.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "2.21.0"
name = var.vpc_name
cidr = var.vpc_cidr
azs = var.vpc_azs
private_subnets = var.vpc_private_subnets
public_subnets = var.vpc_public_subnets
enable_nat_gateway = var.vpc_enable_nat_gateway
tags = var.vpc_tags
}
# defines two EC2 instances within your VPC
module "ec2_instances" {
source = "terraform-aws-modules/ec2-instance/aws"
version = "2.12.0"
name = "my-ec2-cluster"
instance_count = 2
ami = "ami-0c5204531f799e0c6"
instance_type = "t2.micro"
vpc_security_group_ids = [module.vpc.default_security_group_id]
subnet_id = module.vpc.public_subnets[0]
tags = {
Terraform = "true"
Environment = "dev"
}
}
# variables.tf
# Input variable definitions
variable "vpc_name" {
description = "Name of VPC"
type = string
default = "example-vpc"
}
variable "vpc_cidr" {
description = "CIDR block for VPC"
type = string
default = "10.0.0.0/16"
}
variable "vpc_azs" {
description = "Availability zones for VPC"
type = list(string)
default = ["us-west-2a", "us-west-2b", "us-west-2c"]
}
variable "vpc_private_subnets" {
description = "Private subnets for VPC"
type = list(string)
default = ["10.0.1.0/24", "10.0.2.0/24"]
}
variable "vpc_public_subnets" {
description = "Public subnets for VPC"
type = list(string)
default = ["10.0.101.0/24", "10.0.102.0/24"]
}
variable "vpc_enable_nat_gateway" {
description = "Enable NAT gateway for VPC"
type = bool
default = true
}
variable "vpc_tags" {
description = "Tags to apply to resources created by VPC module"
type = map(string)
default = {
Terraform = "true"
Environment = "dev"
}
}
Modules also have output values, which are defined within the module with the output
keyword. You can access them by referring to module.<MODULE NAME>.<OUTPUT NAME>
.
# outputs.tf
# Output variable definitions
output "vpc_public_subnets" {
description = "IDs of the VPC's public subnets"
value = module.vpc.public_subnets
}
output "ec2_instance_public_ips" {
description = "Public IP addresses of EC2 instances"
value = module.ec2_instances.public_ip
}
├── LICENSE
├── README.md
├── main.tf
├── modules
│ └── aws-s3-static-website-bucket
│ ├── LICENSE
│ ├── README.md
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── outputs.tf
└── variables.tf
# modules/aws-s3-static-website-bucket/main.tf
resource "aws_s3_bucket" "s3_bucket" {
bucket = var.bucket_name
acl = "public-read"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::${var.bucket_name}/*"
]
}
]
}
EOF
website {
index_document = "index.html"
error_document = "error.html"
}
tags = var.tags
}
There is no provider
block in this configuration. When Terraform processes a module block, it will inherit the provider from the enclosing configuration. Because of this, we recommend that you do not include provider
blocks in modules.
# modules/aws-s3-static-website-bucket/outputs.tf
# Output variable definitions => module.<MODULE NAME>.<OUTPUT NAME>.
output "arn" {
description = "ARN of the bucket"
value = aws_s3_bucket.s3_bucket.arn
}
output "name" {
description = "Name (id) of the bucket"
value = aws_s3_bucket.s3_bucket.id
}
output "domain" {
description = "Domain name of the bucket"
value = aws_s3_bucket.s3_bucket.website_domain
}
# modules/aws-s3-static-website-bucket/variables.tf
# Input variable definitions
variable "bucket_name" {
description = "Name of the s3 bucket. Must be unique."
type = string
}
variable "tags" {
description = "Tags to set on the bucket."
type = map(string)
default = {}
}
How to use a module:
# main.tf
module "website_s3_bucket" {
source = "./modules/aws-s3-static-website-bucket"
bucket_name = "<UNIQUE BUCKET NAME>"
tags = {
Terraform = "true"
Environment = "dev"
}
}
You provide values to variables defined in the module.
Last updated
Was this helpful?