Terraform
Terraform
Terraform is the infrastructure as code tool from HashiCorp. It is a tool for building, changing,
and managing infrastructure in a safe, repeatable way. Operators and Infrastructure teams can
use Terraform to manage environments with a configuration language called the HashiCorp
Configuration Language (HCL) for human-readable, automated deployments.
»Infrastructure as Code
At a high level, Terraform allows operators to use HCL to author files containing definitions of
their desired resources on almost any provider (AWS, GCP, GitHub, Docker, etc) and automates
the creation of those resources at the time of apply.
»Workflows
A simple workflow for deployment will follow closely to the steps below. We will go over each of
these steps and concepts more in-depth throughout these tutorials, so don't panic if you don't
understand the concepts immediately.
Author - Create the configuration file in HCL based on the scoped parameters
Initialize - Run terraform init in the project directory with the configuration files. This will
download the correct provider plug-ins for the project.
Plan & Apply - Run terraform plan to verify creation process and then terraform apply to create
real resources as well as state file that compares future changes in your configuration files to
what actually exists in your deployment environment.
Advantages of Terraform
While many of the current tools for infrastructure as code may work in your environment,
Terraform aims to have a few advantages for operators and organizations of any size.
Platform Agnostic
State Management
Operator Confidence
»Platform Agnostic
In a modern datacenter, you may have several different clouds and platforms to support your
various applications. With Terraform, you can manage a heterogenous environment with the
same workflow by creating a configuration file to fit the needs of your project or organization.
»State Management
Terraform creates a state file when a project is first initialized. Terraform uses this local state to
create plans and make changes to your infrastructure. Prior to any operation, Terraform does a
refresh to update the state with the real infrastructure. This means that Terraform state is the
source of truth by which configuration changes are measured. If a change is made or a resource
is appended to a configuration, Terraform compares those changes with the state file to
determine what changes result in a new resource or resource modifications.
»Operator Confidence
The workflow built into Terraform aims to instill confidence in users by promoting easily
repeatable operations and a planning phase to allow users to ensure the actions taken by
Terraform will not cause disruption in their environment. Upon terraform apply, the user will be
prompted to review the proposed changes and must affirm the changes or else Terraform will
not apply the proposed plan.
To use Terraform you will need to install it. HashiCorp distributes Terraform as a binary package.
You can also install Terraform using popular package managers.
»Install Terraform
Manual installation
Homebrew on OS X
Chocolatey on Windows
Linux
Pre-compiled binary
To install Terraform, find the appropriate package for your system and download it as a zip
archive.
After downloading Terraform, unzip the package. Terraform runs as a single binary named
terraform. Any other files in the package can be safely removed and Terraform will still function.
Finally, make sure that the terraform binary is available on your PATH. This process will differ
depending on your operating system.
Mac or Linux
Windows
$ echo $PATH
Copy
Move the Terraform binary to one of the listed locations. This command assumes that the
binary is currently in your downloads folder and that your PATH includes /usr/local/bin, but you
can customize it if your locations are different.
$ mv ~/Downloads/terraform /usr/local/bin/
Copy
For more detail about adding binaries to your path, see this Stack Overflow article.
Verify that the installation worked by opening a new terminal session and listing Terraform's
available subcommands.
$ terraform -help
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.
##...
Copy
Add any subcommand to terraform -help to learn more about what it does and available
options.
Add any subcommand to terraform -help to learn more about what it does and available
options.
Copy
»Troubleshoot
If you get an error that terraform could not be found, your PATH environment variable was not
set up properly. Please go back and ensure that your PATH variable contains the directory where
Terraform was installed.
If you use either bash or zsh you can enable tab completion for Terraform commands. To enable
autocomplete, run the following command and then restart your shell.
$ terraform -install-autocomplete
Copy
»Quick start tutorial
Now that you've installed Terraform, you can provision an NGINX server in less than a minute
using Docker on Mac, Windows, or Linux.
After you install Terraform and Docker on your local machine, start Docker Desktop.
$ open -a Docker
Copy
Paste the following Terraform configuration into a file and name it main.tf.
Mac or Linux
Windows
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
provider "docker" {}
name = "nginx:latest"
keep_locally = false
image = docker_image.nginx.latest
name = "tutorial"
ports {
internal = 80
external = 8000
}
Copy
Initialize the project, which downloads a plugin that allows Terraform to interact with Docker.
$ terraform init
Copy
Provision the NGINX server container with apply. When Terraform asks you to confirm type yes
and press ENTER.
$ terraform apply
Copy
Verify the existence of the NGINX container by visiting localhost:8000 in your web browser or
running docker ps to see the container.
$ docker ps
Copy
$ terraform destroy
Copy
Next, you will create real infrastructure in the cloud of your choice.
You will provision an Amazon Machine Image (AMI) on Amazon Web Services
(AWS) in this tutorial, since AMIs are widely used.
»Prerequisites
An AWS account
With your account created and the CLI installed configure the AWS CLI.
$ aws configure
Copy
Follow the prompts to input your AWS Access Key ID and Secret Access Key, which you'll find on
this page.
Note: This tutorial will provision resources that qualify under the AWS free-tier. If your account
doesn't qualify under the AWS free-tier, we're not responsible for any charges that you may
incur.
»Write configuration
Each configuration should be in its own directory. Create a directory for the new configuration.
$ mkdir learn-terraform-aws-instance
Copy
$ cd learn-terraform-aws-instance
Copy
$ touch main.tf
Copy
Paste the configuration below into main.tf and save it. Terraform loads all files in the working
directory that end in .tf.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
provider "aws" {
profile = "default"
region = "us-west-2"
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleInstance"
Copy
This is a complete configuration that Terraform is ready to apply. In the following sections we'll
review each block of the configuration in more detail.
»Terraform Block
The terraform {} block is required so Terraform knows which provider to download from the
Terraform Registry. In the configuration above, the aws provider's source is defined as
hashicorp/aws which is shorthand for registry.terraform.io/hashicorp/aws.
You can also assign a version to each provider defined in the required_providers block. The
version argument is optional, but recommended. It is used to constrain the provider to a specific
version or a range of versions in order to prevent downloading a new provider that may possibly
contain breaking changes. If the version isn't specified, Terraform will automatically download
the most recent provider during initialization.
»Providers
The provider block configures the named provider, in our case aws, which is responsible for
creating and managing resources. A provider is a plugin that Terraform uses to translate the API
interactions with the service. A provider is responsible for understanding API interactions and
exposing resources. Because Terraform can interact with any API, you can represent almost any
infrastructure type as a resource in Terraform.
The profile attribute in your provider block refers Terraform to the AWS credentials stored in
your AWS Config File, which you created when you configured the AWS CLI. HashiCorp
recommends that you never hard-code credentials into *.tf configuration files. We are explicitly
defining the default AWS config profile here to illustrate how Terraform should access sensitive
credentials.
Note: If you leave out your AWS credentials, Terraform will automatically search for saved API
credentials (for example, in ~/.aws/credentials) or IAM instance profile credentials. This is
cleaner when .tf files are checked into source control or if there is more than one admin user.
Multiple provider blocks can exist if a Terraform configuration manages resources from different
providers. You can even use multiple providers together. For example you could pass the ID of
an AWS instance to a monitoring resource from DataDog.
»Resources
The resource block defines a piece of infrastructure. A resource might be a physical component
such as an EC2 instance, or it can be a logical resource such as a Heroku application.
The resource block has two strings before the block: the resource type and the resource name.
In the example, the resource type is aws_instance and the name is example. The prefix of the
type maps to the provider. In our case "aws_instance" automatically tells Terraform that it is
managed by the "aws" provider.
The arguments for the resource are within the resource block. The arguments could be things
like machine sizes, disk image names, or VPC IDs. Our providers reference documents the
required and optional arguments for each resource provider. For your EC2 instance, you
specified an AMI for Ubuntu, and requested a t2.micro instance so you qualify under the free
tier.
When you create a new configuration — or check out an existing configuration from version
control — you need to initialize the directory with terraform init.
$ terraform init
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
rerun this command to reinitialize your working directory. If you forget, other
Copy
Terraform downloads the aws provider and installs it in a hidden subdirectory of the current
working directory. The output shows which version of the plugin was installed.
We recommend using consistent formatting in files and modules written by different teams. The
terraform fmt command automatically updates configurations in the current directory for easy
readability and consistency.
Format your configuration. Terraform will return the names of the files it formatted. In this case,
your configuration file was already formatted correctly, so Terraform won't return any file
names.
$ terraform fmt
Copy
If you are copying configuration snippets or just want to make sure your configuration is
syntactically valid and internally consistent, the built in terraform validate command will check
and report errors within modules, attribute names, and value types.
Validate your configuration. If your configuration is valid, Terraform will return a success
message.
$ terraform validate
Copy
»Create infrastructure
In the same directory as the main.tf file you created, run terraform apply. Terraform will print
output similar to what is shown below, though we've truncated some of the output to save
space.
$ terraform apply
+ ami = "ami-830c94e3"
##...
Enter a value:
Copy
Tip: If your configuration fails to apply, you may have customized your region or removed your
default VPC. Refer to the troubleshooting section at the bottom of this tutorial for help.
This output shows the execution plan, describing which actions Terraform will take in order to
change real infrastructure to match the configuration.
The output format is similar to the diff format generated by tools such as Git. The output has a +
next to aws_instance.example, meaning that Terraform will create this resource. Beneath that,
it shows the attributes that will be set. When the value displayed is (known after apply), it
means that the value won't be known until the resource is created.
Terraform will now pause and wait for your approval before proceeding. If anything in the plan
seems incorrect or dangerous, it is safe to abort here with no changes made to your
infrastructure.
In this case the plan is acceptable, so type yes at the confirmation prompt to proceed. Executing
the plan will take a few minutes since Terraform waits for the EC2 instance to become available.
aws_instance.example: Creating...
You've now created infrastructure using Terraform! Visit the EC2 console and find the new EC2
instance. Make sure the console is set to the same region that was configured in the provider
configuration!
»Inspect state
When you applied your configuration, Terraform wrote data into a file called terraform.tfstate.
This file now contains the IDs and properties of the resources Terraform created so that it can
manage or destroy those resources going forward.
You must save your state file securely and distribute it only to trusted team members who need
to manage your infrastructure. In production, we recommend storing your state remotely.
Remote stage storage enables collaboration using Terraform but is beyond the scope of this
tutorial.
$ terraform show
# aws_instance.example:
ami = "ami-830c94e3"
arn = "arn:aws:ec2:us-west-2:561656980159:instance/i-01e03375ba238b384"
associate_public_ip_address = true
availability_zone = "us-west-2c"
cpu_core_count =1
cpu_threads_per_core =1
disable_api_termination = false
ebs_optimized = false
get_password_data = false
hibernation = false
id = "i-01e03375ba238b384"
instance_state = "running"
instance_type = "t2.micro"
ipv6_address_count =0
ipv6_addresses = []
monitoring = false
primary_network_interface_id = "eni-068d850de6a4321b7"
private_dns = "ip-172-31-0-139.us-west-2.compute.internal"
private_ip = "172.31.0.139"
public_dns = "ec2-18-237-201-188.us-west-2.compute.amazonaws.com"
public_ip = "18.237.201.188"
secondary_private_ips = []
security_groups =[
"default",
source_dest_check = true
subnet_id = "subnet-31855d6c"
tags ={
"Name" = "ExampleInstance"
tenancy = "default"
vpc_security_group_ids =[
"sg-0edc8a5a",
credit_specification {
cpu_credits = "standard"
}
enclave_options {
enabled = false
metadata_options {
http_endpoint = "enabled"
http_put_response_hop_limit = 1
http_tokens = "optional"
root_block_device {
delete_on_termination = true
device_name = "/dev/sda1"
encrypted = false
iops =0
tags = {}
throughput =0
volume_id = "vol-031d56cc45ea4a245"
volume_size =8
volume_type = "standard"
}
Copy
When Terraform created this EC2 instance, it also gathered a lot of information about it. These
values can be referenced to configure other resources or outputs, which we discuss more later
on in these tutorials.
Terraform has a built in command called terraform state for advanced state management. For
example, if you have a long state file, you may want a list of the resources in state, which you
can get by using the list subcommand.
aws_instance.example
Copy
»Troubleshooting
If terraform validate was successful and your apply still failed, you may be encountering a
common error.
If you use a region other than us-east-1, you will also need to change your ami, since AMI IDs
are region specific. Choose an AMI ID specific to your region by following these instructions, and
modify main.tf with this ID. Then re-run terraform apply.
If you do not have a default VPC in your AWS account in the correct region, navigate to the AWS
VPC Dashboard in the web UI, create a new VPC in your region, and associate a subnet and
security group to that VPC. Then add the security group ID (vpc_security_group_ids) and subnet
ID (subnet_id) into your aws_instance resource, and replace the values with the ones from your
new security group and subnet.
instance_type = "t2.micro"
+ vpc_security_group_ids = ["sg-0077..."]
+ subnet_id = "subnet-923a..."
Remember to add these lines to your configuration for the rest of the get started track. For
more information, review this document from AWS on working with VPCs.
»Next Steps
Now that you have created your first infrastructure using Terraform, continue to the next
tutorial to modify your infrastructure.
Read about the format of the configuration files in the terraform documentation.
Find examples of Terraform configurations using multiple providers in the documentation use
cases section.
Read this blog post and these docs to learn more about AWS authentication.
For more information about the terraform state command and subcommands for moving or
removing resources from state, see the CLI state command documentation.
https://learn.hashicorp.com/tutorials/terraform/aws-change?in=terraform/aws-get-started
Change Infrastructure
In the previous page, you created your first infrastructure with Terraform: a single EC2 instance.
In this page, we're going to modify that resource, and see how Terraform handles change.
Infrastructure is continuously evolving, and Terraform was built to help manage and enact that
change. As you change Terraform configurations, Terraform builds an execution plan that only
modifies what is necessary to reach your desired state.
By using Terraform to change infrastructure, you can version control not only your
configurations but also your state so you can see how the infrastructure evolved over time.
»Prerequisites
This tutorial assumes that you're continuing from the previous tutorials. If not, create a
directory named learn-terraform-aws-instance and paste this code into a file named main.tf.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
provider "aws" {
profile = "default"
region = "us-west-2"
}
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleInstance"
Copy
»Configuration
Now update the ami of your instance. Change the aws_instance.example resource under the
provider block in main.tf by replacing the current AMI ID with a new one.
Tip: The below snippet is formatted as a diff to give you context about what in your
configuration should change. Replace the content displayed in red with the content displayed in
green (exclude the leading + and - signs).
- ami = "ami-830c94e3"
+ ami = "ami-08d70e59c07c61a3a"
instance_type = "t2.micro"
This update changes the AMI to an Ubuntu 16.04 AMI. The AWS provider knows that it cannot
change the AMI of an instance after it has been created, so Terraform will destroy the old
instance and create a new one.
»Apply Changes
After changing the configuration, run terraform apply again to see how Terraform will apply this
change to the existing resources.
$ terraform apply
~ arn = "arn:aws:ec2:us-west-2:561656980159:instance/i-
01e03375ba238b384" -> (known after apply)
##...
Copy
The prefix -/+ means that Terraform will destroy and recreate the resource, rather than
updating it in-place. While some attributes can be updated in-place (which are shown with the
~ prefix), changing the AMI for an EC2 instance requires recreating it. Terraform handles these
details for you, and the execution plan makes it clear what Terraform will do.
Additionally, the execution plan shows that the AMI change is what required your resource to
be replaced. Using this information, you can adjust your changes to possibly avoid
destroy/create updates if they are not acceptable in some situations.
Once again, Terraform prompts for approval of the execution plan before proceeding. Answer
yes to execute the planned steps:
aws_instance.example: Creating...
As indicated by the execution plan, Terraform first destroyed the existing instance and then
created a new one in its place. You can use terraform show again to see the new values
associated with this instance.
Destroy Infrastructure
We've now seen how to build and change infrastructure. Before we move on to creating
multiple resources and showing resource dependencies, we're going to go over how to
completely destroy the Terraform-managed infrastructure.
Destroying your infrastructure is a rare event in production environments. But if you're using
Terraform to spin up multiple environments such as development, test, QA environments, then
destroying is a useful action.
»Destroy
The terraform destroy command terminates resources defined in your Terraform configuration.
This command is the reverse of terraform apply in that it terminates all the resources specified
by the configuration. It does not destroy resources running elsewhere that are not described in
the current configuration.
$ terraform destroy
- destroy
- arn = "arn:aws:ec2:us-west-2:561656980159:instance/i-
0fd4a35969bd21710" -> null
##...
Enter a value:
Copy
The - prefix indicates that the instance will be destroyed. As with apply, Terraform shows its
execution plan and waits for approval before making any changes.
Just like with apply, Terraform determines the order in which things must be destroyed. In this
case there was only one resource, so no ordering was necessary. In more complicated cases
with multiple resources, Terraform will destroy them in a suitable order to respect
dependencies.
You now have enough Terraform knowledge to create useful configurations, but the examples so
far have used hard-coded values. Terraform configurations can include variables to make your
configuration more dynamic and flexible.
»Prerequisites
After following the other tutorials in this collection, you will have a directory named learn-
terraform-aws-instance with the following configuration in a file called main.tf.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
provider "aws" {
profile = "default"
region = "us-west-2"
ami = "ami-08d70e59c07c61a3a"
instance_type = "t2.micro"
tags = {
Name = "ExampleInstance"
Copy
Ensure that your configuration matches this, and that you have run terraform init in the learn-
terraform-aws-instance directory.
The configuration includes a number of hard-coded values. Terraform variables allow you to
write configuration that is flexible and easier to re-use.
Create a new file called variables.tf with a block defining a new instance_name variable.
variable "instance_name" {
type = string
default = "ExampleInstance"
Copy
Note: Terraform loads all files in the current directory ending in .tf, so you can name your
configuration files however you choose.
In main.tf, update the aws_instance resource block to use the new variable.
ami = "ami-08d70e59c07c61a3a"
instance_type = "t2.micro"
tags = {
- Name = "ExampleInstance"
+ Name = var.instance_name
$ terraform apply
+ create
+ ami = "ami-08d70e59c07c61a3a"
##...
aws_instance.example: Creating...
Copy
Now apply the configuration again. Terraform will update the instance with the new Name tag
with the value of the instance_type variable using the -var flag. Respond to the confirmation
prompt with yes.
~ update in-place
id = "i-0bf954919ed765de1"
~ tags ={
}
Plan: 0 to add, 1 to change, 0 to destroy.
Copy
Setting variables via the command-line will not save the new value, so you will need to set them
have to be entered repeatedly as commands are executed.
Terraform supports many ways to use and set variables. To learn more, follow our in-depth
tutorial, Customize Terraform Configuration with Variables.