You are on page 1of 34

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

If you are new to infrastructure as code as a concept, it is the process of managing


infrastructure in a file or files rather than manually configuring resources in a user interface. A
resource in this instance is any piece of infrastructure in a given environment, such as a virtual
machine, security group, network interface, etc.

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.

Scope - Confirm what resources need to be created for a given project.

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

Retrieve the terraform binary by downloading a pre-compiled binary or compiling it from


source.

Pre-compiled binary

Compile from source

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

Print a colon-separated list of locations in your PATH.

$ 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 the installation

Verify that the installation worked by opening a new terminal session and listing Terraform's
available subcommands.

$ terraform -help

Usage: terraform [-version] [-help] <command> [args]


The available commands for execution are listed below.

The most common, useful commands are shown first, followed by

less common or more advanced commands. If you're just getting

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.

$ terraform -help plan

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.

»Enable tab completion

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.

Docker Desktop for Mac

Docker Desktop for Windows

Download Docker Desktop for Mac.

After you install Terraform and Docker on your local machine, start Docker Desktop.

$ open -a Docker

Create a directory named terraform-docker-demo.

$ mkdir terraform-docker-demo && cd $_

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" {}

resource "docker_image" "nginx" {

name = "nginx:latest"

keep_locally = false

resource "docker_container" "nginx" {

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.

NGINX running in Docker via Terraform

$ docker ps

CONTAINER ID IMAGE COMMAND CREATED STATUS


PORTS NAMES

425d5ee58619 e791337790a6 "nginx -g 'daemon of…" 20 seconds ago Up 19


seconds 0.0.0.0:8000->80/tcp tutorial

Copy

To stop the container, run terraform destroy.

$ terraform destroy

Copy

You've now provisioned and destroyed an NGINX webserver with Terraform.


»Next Steps

Next, you will create real infrastructure in the cloud of your choice.

With Terraform installed, you're ready to create your first infrastructure.

You will provision an Amazon Machine Image (AMI) on Amazon Web Services
(AWS) in this tutorial, since AMIs are widely used.

»Prerequisites

To follow this tutorial you will need:

An AWS account

The AWS CLI installed

Your AWS credentials configured locally.

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.

The configuration process creates a file at ~/.aws/credentials on MacOS and Linux or


%UserProfile%\.aws\credentials on Windows, where your credentials are stored.

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

The set of files used to describe infrastructure in Terraform is known as a


Terraform configuration. You'll write your first configuration now to launch a single AWS EC2
instance.

Each configuration should be in its own directory. Create a directory for the new configuration.

$ mkdir learn-terraform-aws-instance

Copy

Change into the directory.

$ cd learn-terraform-aws-instance

Copy

Create a file for the configuration code.

$ 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"

version = "~> 3.27"

}
}

provider "aws" {

profile = "default"

region = "us-west-2"

resource "aws_instance" "example" {

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.

To learn more, reference the provider source documentation.

»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.

»Initialize the directory

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 uses a plugin-based architecture to support hundreds of infrastructure and service


providers. Initializing a configuration directory downloads and installs providers used in the
configuration, which in this case is the aws provider. Subsequent commands will use local
settings and data during initialization.

Initialize the directory.

$ terraform init

Initializing the backend...

Initializing provider plugins...


- Finding hashicorp/aws versions matching "~> 3.27"...

- Installing hashicorp/aws v3.27.0...

- Installed hashicorp/aws v3.27.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider

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 run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see

any changes that are required for your infrastructure. All Terraform commands

should now work.

If you ever set or change modules or backend configuration for Terraform,

rerun this command to reinitialize your working directory. If you forget, other

commands will detect it and remind you to do so if necessary.

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.

»Format and validate the configuration

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

Success! The configuration is valid.

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

An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:


+ create

Terraform will perform the following actions:

# aws_instance.example will be created

+ resource "aws_instance" "example" {

+ ami = "ami-830c94e3"

+ arn = (known after apply)

##...

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?

Terraform will perform the actions described above.

Only 'yes' will be accepted to approve.

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.

Enter a value: yes

aws_instance.example: Creating...

aws_instance.example: Still creating... [10s elapsed]

aws_instance.example: Still creating... [20s elapsed]

aws_instance.example: Still creating... [30s elapsed]

aws_instance.example: Creation complete after 36s [id=i-01e03375ba238b384]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

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.

Inspect the current state using terraform show.

$ terraform show

# aws_instance.example:

resource "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.

»Manually Managing State

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.

$ terraform state list

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.

resource "aws_instance" "example" {


ami = "ami-830c94e3"

instance_type = "t2.micro"

+ vpc_security_group_ids = ["sg-0077..."]

+ subnet_id = "subnet-923a..."

Save the changes to main.tf, and re-run terraform apply.

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.

For more detail on the concepts we used in this tutorial:

Read about the format of the configuration files in the terraform documentation.

Learn more about Terraform providers.

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"

version = "~> 3.27"

provider "aws" {

profile = "default"

region = "us-west-2"
}

resource "aws_instance" "example" {

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).

resource "aws_instance" "example" {

- 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

aws_instance.example: Refreshing state... [id=i-01e03375ba238b384]

An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

-/+ destroy and then create replacement

Terraform will perform the following actions:

# aws_instance.example must be replaced

-/+ resource "aws_instance" "example" {

~ ami = "ami-830c94e3" -> "ami-08d70e59c07c61a3a" # forces replacement

~ arn = "arn:aws:ec2:us-west-2:561656980159:instance/i-
01e03375ba238b384" -> (known after apply)

##...

Plan: 1 to add, 0 to change, 1 to destroy.

Do you want to perform these actions?

Terraform will perform the actions described above.

Only 'yes' will be accepted to approve.


Enter a value:

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:

Enter a value: yes+

aws_instance.example: Destroying... [id=i-01e03375ba238b384]

aws_instance.example: Still destroying... [id=i-01e03375ba238b384, 10s elapsed]

aws_instance.example: Still destroying... [id=i-01e03375ba238b384, 20s elapsed]

aws_instance.example: Still destroying... [id=i-01e03375ba238b384, 30s elapsed]

aws_instance.example: Still destroying... [id=i-01e03375ba238b384, 40s elapsed]

aws_instance.example: Destruction complete after 42s

aws_instance.example: Creating...

aws_instance.example: Still creating... [10s elapsed]

aws_instance.example: Still creating... [20s elapsed]

aws_instance.example: Still creating... [30s elapsed]

aws_instance.example: Still creating... [40s elapsed]

aws_instance.example: Creation complete after 50s [id=i-0fd4a35969bd21710]


Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

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

An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

- destroy

Terraform will perform the following actions:


# aws_instance.example will be destroyed

- resource "aws_instance" "example" {

- ami = "ami-08d70e59c07c61a3a" -> null

- arn = "arn:aws:ec2:us-west-2:561656980159:instance/i-
0fd4a35969bd21710" -> null

##...

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?

Terraform will destroy all your managed infrastructure, as shown above.

There is no undo. Only 'yes' will be accepted to confirm.

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.

Answer yes to execute this plan and destroy the infrastructure.

Enter a value: yes

aws_instance.example: Destroying... [id=i-0fd4a35969bd21710]

aws_instance.example: Still destroying... [id=i-0fd4a35969bd21710, 10s elapsed]

aws_instance.example: Still destroying... [id=i-0fd4a35969bd21710, 20s elapsed]

aws_instance.example: Still destroying... [id=i-0fd4a35969bd21710, 30s elapsed]


aws_instance.example: Destruction complete after 31s

Destroy complete! Resources: 1 destroyed.

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.

Define Input Variables

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"

version = "~> 3.27"

}
provider "aws" {

profile = "default"

region = "us-west-2"

resource "aws_instance" "example" {

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.

»Set the instance name with a variable

The configuration includes a number of hard-coded values. Terraform variables allow you to
write configuration that is flexible and easier to re-use.

Add a variable to define the instance name.

Create a new file called variables.tf with a block defining a new instance_name variable.

variable "instance_name" {

description = "Value of the Name tag for the EC2 instance"

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.

resource "aws_instance" "example" {

ami = "ami-08d70e59c07c61a3a"

instance_type = "t2.micro"

tags = {

- Name = "ExampleInstance"

+ Name = var.instance_name

Apply the configuration. Respond to the confirmation prompt with a yes.

$ terraform apply

An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

+ create

Terraform will perform the following actions:


# aws_instance.example will be created

+ resource "aws_instance" "example" {

+ ami = "ami-08d70e59c07c61a3a"

+ arn = (known after apply)

##...

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?

Terraform will perform the actions described above.

Only 'yes' will be accepted to approve.

Enter a value: yes

aws_instance.example: Creating...

aws_instance.example: Still creating... [10s elapsed]

aws_instance.example: Still creating... [20s elapsed]

aws_instance.example: Still creating... [30s elapsed]

aws_instance.example: Still creating... [40s elapsed]

aws_instance.example: Creation complete after 50s [id=i-0bf954919ed765de1]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

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.

$ terraform apply -var 'instance_name=YetAnotherName'

aws_instance.example: Refreshing state... [id=i-0bf954919ed765de1]

An execution plan has been generated and is shown below.

Resource actions are indicated with the following symbols:

~ update in-place

Terraform will perform the following actions:

# aws_instance.example will be updated in-place

~ resource "aws_instance" "example" {

id = "i-0bf954919ed765de1"

~ tags ={

~ "Name" = "ExampleInstance" -> "YetAnotherName"

# (26 unchanged attributes hidden)

# (4 unchanged blocks hidden)

}
Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?

Terraform will perform the actions described above.

Only 'yes' will be accepted to approve.

Enter a value: yes

aws_instance.example: Modifying... [id=i-0bf954919ed765de1]

aws_instance.example: Modifications complete after 7s [id=i-0bf954919ed765de1]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

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.

You might also like