DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • An Introduction to Terraform's Core Concepts
  • Terraform Best Practices: The 24 Practices You Should Adopt
  • Auto-Scaling a Spring Boot Native App With Nomad
  • 5 Best Node.js Practices to Develop Scalable and Robust Applications

Trending

  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Using Python Libraries in Java
  • Measuring the Impact of AI on Software Engineering Productivity
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Terraform CLI Cheat Sheet

Terraform CLI Cheat Sheet

If all you need is a quick look, take a look at this reference article for Terraform CLI.

By 
Aurelie Vache user avatar
Aurelie Vache
·
Dec. 19, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
94.8K Views

Join the DZone community and get the full member experience.

Join For Free

When we want to use a tool or improve our expertise in a particular technology, it's good to read a lot of articles and, of course, to manipulate the technology.

But sometimes, it can be useful to have a simple cheat sheet of the tool.

You might also enjoy Linode's Beginner's Guide to Terraform.

About Terraform CLI

Terraform, a tool created by Hashicorp in 2014, written in Go, aims to build, change and version control your infrastructure. This tool has a powerful and very intuitive Command Line Interface.

Installation

Install Through curl

$ curl -O https://releases.hashicorp.com/terraform/0.11.10/terraform_0.11.10_linux_amd64.zip
$ sudo unzip terraform_0.11.10_linux_amd64.zip -d /usr/local/bin/
$ rm terraform_0.11.10_linux_amd64.zip


...or Install Through tfenv, a Terraform Version Manager

First of all, download the tfenv binary and put it in your PATH.

$ git clone https://github.com/Zordrak/tfenv.git ~/.tfenv
$ echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> $HOME/bashrc


Then, you can install the desired version of Terraform:

$ tfenv install 0.11.10

Usage

Show Version

$ terraform --version
 Terraform v0.11.10

Init Terraform

$ terraform init

It’s the first command you need to execute. Unless  terraform plan , apply  , destroy   and import  will not work. The command terraform init   will install :

  • Terraform modules
  • Eventually a backend
  • Provider(s) plugins

Init Terraform and Don’t Ask Any Input

$ terraform init -input=false

Change Backend Configuration During the Init

$ terraform init -backend-config=cfg/s3.dev.tf -reconfigure

-reconfigure is used in order to tell Terraform to not copy the existing state to the new remote state location.

Get

This command is useful when you have defined some modules. Modules are vendored, so when you edit them, you need to get again modules content.

$ terraform get -update=true

When you use modules, the first thing you’ll have to do is to do a  terraform get . This pulls modules into the .terraform directory. Once you do that, unless you do another terraform get -update=true, you’ve essentially vendored those modules.

Plan

The plan step check configuration to execute and write a plan to apply to target infrastructure provider.

$ terraform plan -out plan.out

It’s an important feature of Terraform that allows a user to see which actions Terraform will perform prior to making any changes, increasing confidence that a change will have the desired effect once applied.

When you execute terraform plan, Terraform will scan all *.tf files in your directory and create the plan.

Apply

Now you have the desired state so you can execute the plan.

$ terraform apply plan.out

Good to know: Since Terraform v0.11+, in an interactive mode (non CI/CD/autonomous pipeline), you can just execute terraform apply command which will print out which actions TF will perform.

By generating the plan and applying it in the same command, Terraform can guarantee that the execution plan won’t change, without needing to write it to disk. This reduces the risk of potentially-sensitive data being left behind, or accidentally checked into version control.

$ terraform apply

Apply and Auto Approve

$ terraform apply -auto-approve

Apply and Define New Variables Value

$ terraform apply -auto-approve -var tags-repository_url=${GIT_URL}


Apply Only One Module

$ terraform apply -target=module.s3


This -target option works with Terraform plan too.

Destroy

$ terraform destroy

Delete all the resources!

A deletion plan can be created before:

$ terraform plan –destroy

-target option allows to destroy only one resource, for example, an S3 bucket :

$ terraform destroy -target aws_s3_bucket.my_bucket


Debug

The terraform console  command is useful for testing interpolations before using them in configurations. Terraform console will read configured state even if it is remote.

$ echo "aws_iam_user.notif.arn" | terraform console
arn:aws:iam::123456789:user/notif


Graph

$ terraform graph | dot –Tpng > graph.png

Visual dependency graph of Terraform resources.

Validate

The validate command is used to validate/check the syntax of the Terraform files. A syntax check is done on all the Terraform files in the directory and will display an error if any of the files don’t validate. The syntax check does not cover every syntax common issues.

$ terraform validate


Providers

You can use a lot of providers/plugins in your Terraform definition resources, so it can be useful to have a tree of providers used by modules in your project.

$ terraform providers
.
├── provider.aws ~> 1.24.0
├── module.my_module
│   ├── provider.aws (inherited)
│   ├── provider.null
│   └── provider.template
└── module.elastic
    └── provider.aws (inherited)


State

Pull Remote State in A Local Copy

$ terraform state pull > terraform.tfstate


Push State in a Remote Backend storage

$ terraform state push


This command is useful if, for example, you originally use a local tf state and then you define backend storage, in S3 or Consul…

How to Tell to Terraform You Moved a Resource in A Module?

If you moved an existing resource in a module, you need to update the state:

$ terraform state mv aws_iam_role.role1 module.mymodule


How to Import Existing Resource in Terraform?

If you have an existing resource in your infrastructure provider, you can import it in your Terraform state:

$ terraform import aws_iam_policy.elastic_post
arn:aws:iam::123456789:policy/elastic_post


Workspaces

To manage multiple distinct sets of infrastructure resources/environments.

Instead of creating a directory for each environment to manage, we need to just create needed workspace and use them:

Create Workspace

This command creates a new workspace and then select it

$ terraform workspace new dev

Select a Workspace

$ terraform workspace select dev

List Workspaces


$ terraform workspace list
  default
* dev
  preprod


Show Current Workspace


$ terraform workspace show
dev


Tools

jq

jq is a lightweight command-line JSON processor. Combined with Terraform output it can be powerful.

Installation

For Linux:

$ sudo apt-get install jq

or

$ yum install jq

For OS X:

$ brew install jq

Usage

For example, we defined outputs in a module and when we execute terraform apply outputs are displayed:


$ terraform apply
...
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

elastic_endpoint = vpc-toto-12fgfd4d5f4ds5fngetwe4.eu-central-1.es.amazonaws.com


We can extract the value that we want in order to use it in a script for example. With jq it’s easy:

$ terraform output -json
{
    "elastic_endpoint": {
        "sensitive": false,
        "type": "string",
        "value": "vpc-toto-12fgfd4d5f4ds5fngetwe4.eu-central-1.es.amazonaws.com"
    }
}

$ terraform output -json | jq '.elastic_endpoint.value'
"vpc-toto-12fgfd4d5f4ds5fngetwe4.eu-central-1.es.amazonaws.com"


Terraforming

If you have an existing AWS accountl for examples with existing components like S3 buckets, SNS, VPC … You can use Terraforming tool, a tool written in Ruby, which extracts existing AWS resources and converts it to Terraform files!

Installation

$ sudo apt install ruby or $ sudo yum install ruby

and

$ gem install terraforming


Usage

Pre-requisites:

Like for Terraform, you need to set AWS credentials:

$ export AWS_ACCESS_KEY_ID="an_aws_access_key"
$ export AWS_SECRET_ACCESS_KEY="a_aws_secret_key"
$ export AWS_DEFAULT_REGION="eu-central-1"


You can also specify credential profile in ~/.aws/credentials_s and with _–profile option.

$ cat ~/.aws/credentials
[aurelie]
aws_access_key_id = xxx
aws_secret_access_key = xxx
aws_default_region = eu-central-1


$ terraforming s3 --profile aurelie


Usage

$ terraforming --help
Commands:
terraforming alb # ALB
...
terraforming vgw # VPN Gateway
terraforming vpc # VPC


Example:

$ terraforming s3 > aws_s3.tf


Remarks: As you can see, Terraforming can’t extract API gateway resources for the moment so you need to write it manually.

The complete and up-to-date cheat sheet is available in PDF format.

Terraform (software) Command-line interface

Opinions expressed by DZone contributors are their own.

Related

  • An Introduction to Terraform's Core Concepts
  • Terraform Best Practices: The 24 Practices You Should Adopt
  • Auto-Scaling a Spring Boot Native App With Nomad
  • 5 Best Node.js Practices to Develop Scalable and Robust Applications

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!