Guide to Terraform's Plan and AWS VPC Creation Workflow (2024)

Guide to Terraform's Plan and AWS VPC Creation Workflow (1)

Terraform is an open-source, cloud-agnostic provisioning tool developed by HashiCorp and written in the GO language. In this blog, we will talk about the workflow of Terraform. It is extremely helpful in a team and can benefit you even if you work individually. A good workflow enables you to streamline a process, organize it, and make it less error-prone.

In this blog, I will be covering the workflow of Terraform with an example of how to implement it:

Basic Concept of Terraform Workflow | Terraform Plan |Writing Terraform Code | terraform init |terraform destroy | Demo: Creating an AWS VPC

Basic Concept of Terraform Workflow

The workflows of Terraform are built on top of five key steps: Write, Init, Plan, Apply, and Destroy. Nevertheless, their details and actions vary between workflows.

Guide to Terraform's Plan and AWS VPC Creation Workflow (2)

Writethis is whereyou createchanges to the code.

Init – this is where you initialize your code to download the requirements mentioned in your code.

Planthis is where you review changesand choosewhetherto simply acceptthem.

Applythis is where you accept changes and apply them against real infrastructure.

Destroy – this is where to destroy all your created infrastructure.

Also Read:Our blog post on Terraform Tips and Tricks.

Writing Terraform Code

The first thing in the Terraform workflow is to start with writing your Terraform configuration just like you write code: in your editor of choice. It’s common practice to store your work in a version-controlled repository even when you’re just operating as an individual.

Note: Check out the blog on Terraform Installation Overview

What Does the Terraform Init Command Do?

The working directory holding the Terraform configuration files is initialized using the terraform init command. After creating a new Terraform configuration or cloning an existing one from version control, this is the first command that needs to be executed. It is safe to execute this command more than once. This command performs multiple distinct startup processes in order to prepare the current working directory for use with Terraform. This command is always safe to run numerous times to bring the working directory up to date with configuration changes. Though additional runs may result in errors, this program will never erase your existing setup or state.

This command, by default, assumes that the working directory already includes a configuration and attempts to initialize it. It can also be run against an empty directory with the -from-module=MODULE-SOURCE option, which copies the supplied module into the target directory before any additional initialization steps are performed.

The majority of providers are available as Terraform plugins. Terraform scans the configuration for both direct and indirect references to providers and attempts to install the plugins for those providers once the command is executed. The program will automatically discover, download, and install the appropriate provider plugins for providers that are published in either the public Register or a third-party provider registry.

Terraform adds information about the selected providers to the dependency lock file after successful installation. You should committhis file to your version control system to ensure that when you run terraform init again in the future, Terraform will choose the same provider versions.

You can use the init command for:

  1. Plugin Installation
  2. Child Module Installation
  3. Backend Initialization

Note: If any of the above changes are done in the configuration then we need to run the init command to initialize the working directory again.

Once you run the command it will begin initializing the directory as shown in the below image.

Guide to Terraform's Plan and AWS VPC Creation Workflow (3)

Also read, our blog on Terraform Providers Overview

How to Create a Terraform Plan?

The terraform plan command generates an execution plan, allowing you to see a preview of the infrastructure modifications that Terraform intends to make. As soon as Terraform produces a plan, it:

  1. Reads the current state of any existing remote objects to ensure that the state is up to date.
  2. Compares the current state to the previous state, noting any differences.
  3. Proposes a set of change actions that, if executed, should cause the remote objects to match the configuration.

The plan command by itself won’t really implement the suggested changes, so before applying them or sharing your changes with your team for wider evaluation, you can use this command to see if the suggested changes line up with your expectations.If the Terraform discovers no changes to resources, then the terraform plan indicates that no changes are required to the real infrastructure.

Terraform also helps to save the plan to a file for later execution with terrafom apply, which can be useful while applying automation with Terraform. This can be achieved by using -out argument. A speculative plan, which is a description of the plan’s effects but with no intention of actually implementing them, will be created if you run the Terraform Plan without the -out=FILE option.

To specify values for input variables declared in your root module, use the -var command-line option. However, doing so will require creating a command line that can be read by Terraform as well as your preferred command-line shell, which can be challenging for expressions with numerous quotes and escape sequences. Instead of interpreting the output of your shell’s parsing, Terraform should be able to parse your actual values directly if you use the -var-file option, which is what we generally advise.

Guide to Terraform's Plan and AWS VPC Creation Workflow (4)

Also Check: Terraform Create VM.

How to use Terraform Apply –

The steps suggested in a Terraform plan are carried out using the Terraform apply command. The simplest approach to use terraform apply is to execute it without any arguments at all. In this instance, it will automatically generate a new execution plan (just as if you had executed the terraform plan) and then ask for your approval before carrying out the stated actions.

The filename of a saved plan file you earlier prepared with terraform plan -out=… can also be passed to terraform apply, in which case Terraform will apply the changes to the plan without asking for confirmation. This two-step process is primarily meant to be used with automated Terraform execution. This command will produce its own plan of action in the default scenario, similar to how terraform plan would in the absence of a saved plan file. Unless you want to forego the prompt by using the -auto-approve option, Terraform will propose the plan to you and prompt you to approve it before carrying out the indicated steps.

The steps described by a plan file are carried out exactly by the command if you pass the filename of a previously saved plan file. You can use terraform display to view a plan file before applying it; it does not prompt for approval. None of the planning modes or planning options referenced above is supported when utilizing a saved plan; these options only have an impact on Terraform’s decisions regarding which actions to take, and the plan file includes the outcomes of those choices.

If you do not provide a plan file on the instruction, terraform apply will create a replacement plan automatically and then prompt for approval to use it. If the created plan does not include any changes to resources or to root module output values then terraform apply will exit immediately, without prompting.

Guide to Terraform's Plan and AWS VPC Creation Workflow (5)

Also Read: Terraform Cheat Sheet.

When to use Terraform destroy?

The terraform destroy command allows you to easily destroy all remote objects managed by a specific Terraform configuration. While you should avoid destroying long-lived objects in a production environment, Terraform is occasionally used to manage ephemeral infrastructure for development reasons, in which case you can use terraform destroy to conveniently wipe away all of those temporary objects after you’re done.

To destroy a specific EC2 instance (demo vm 1), use the –target parameter with the resource path to identify the relevant resource, as shown below.

Terraform destroy is a command that should be used with caution. It is not something that would be used on a daily basis in the industrial setting. However, using it in sub-production contexts would be rather common, as many proof-of-concept tests necessitate cleanup tasks.

Guide to Terraform's Plan and AWS VPC Creation Workflow (6)

Check Out:Terraform Interview Questions and Answers.

Demo: Creating an AWS VPC

We will be performing a simple demo of creating an AWS VPC, to see the terraform workflow:

We can write our terraform configuration in Hashicorp Configuration Language (HCL) or in JSON. Terraform language syntax is built around two key syntax constructs: arguments and blocks.

Read: AWS Virtual Private Cloud (VPC)

1. Create a main.tf file in your favorite editor, and paste the provider block it in.

Guide to Terraform's Plan and AWS VPC Creation Workflow (7)

2. Paste the code of vpc resource in main.tf (Note: You can also name your vpc in AWS using name tag as shown below).

resource "aws_vpc" "demo" { cidr_block = "10.0.0.0/16" instance_tenancy = "default" tags = { Name = "my-first-vpc" }}

Guide to Terraform's Plan and AWS VPC Creation Workflow (8)

3. Run the terraform init command to initialize the code, and download the plugin.

Guide to Terraform's Plan and AWS VPC Creation Workflow (9)

4. Run terraform apply on the terminal to execute the code, and type yes when asked for confirmation.

Guide to Terraform's Plan and AWS VPC Creation Workflow (10)

5. We will get the below output once the vpc is created.

Guide to Terraform's Plan and AWS VPC Creation Workflow (11)

6. Open AWS console, click on Services, and select VPC.

Guide to Terraform's Plan and AWS VPC Creation Workflow (12)

7. Click on Your VPCs and now check for the created VPC.

Guide to Terraform's Plan and AWS VPC Creation Workflow (13)

8. The last step is to delete the infrastructure, you can do this by using terraform destroy command.

Guide to Terraform's Plan and AWS VPC Creation Workflow (14)

Frequently Asked Questions

How does Terraform work?

Terraform works by reading infrastructure configuration files written in HashiCorp Configuration Language (HCL) or JSON. It then creates an execution plan based on the desired state specified in the configuration. The plan outlines the changes necessary to achieve the desired state. Finally, Terraform applies the plan to create, modify, or destroy resources accordingly.

What are the key components of a Terraform workflow?

The key components of a Terraform workflow include: Configuration Files: These define the desired state of your infrastructure. Initialization: This step sets up the working directory and initializes Terraform. Planning: Terraform generates an execution plan that describes the actions it will take. Applying: Terraform applies the execution plan to create or modify the infrastructure. State Management: Terraform stores the state of the infrastructure to track changes and perform updates. Collaboration: Terraform allows teams to work together on infrastructure configurations using version control systems.

What is the difference between Terraform plan and Terraform apply?

Terraform plan creates an execution plan that shows the proposed changes to the infrastructure without actually making any changes. It allows you to review and validate the changes before applying them. Terraform apply, on the other hand, applies the changes described in the execution plan to create, modify, or delete resources in the infrastructure.

How do I initialize a Terraform project?

To initialize a Terraform project, navigate to the project directory in the command line and run the command terraform init. This command initializes the working directory, downloads the necessary provider plugins, and sets up the backend configuration for storing the Terraform state.

What is the purpose of Terraform state?

The Terraform state is a crucial component of the workflow. It stores information about the infrastructure resources Terraform manages. This state is used to create an execution plan, track changes, and perform updates. It is recommended to store the state remotely, such as in a version-controlled object storage or a remote state backend like AWS S3 or HashiCorp Consul.

Can I use variables in my Terraform configurations?

Yes, Terraform supports variables. You can define variables in your configuration files or in separate variable files. Variables can be used to parameterize your infrastructure configurations, making them more reusable and flexible. They can be assigned default values or populated from environment variables or command-line arguments.

Related/References

  • Variables In Terraform
  • Terraform Installation Overview
  • Why Terraform? Not Chef, Ansible, Puppet, CloudFormation?
  • HashiCorp Infrastructure Automation Certification: Terraform Associate
  • Terraform Providers Overview

Join FREE Class

🚀 Master Terraform & DevOps to get High-Paying Jobs!

🔥 Join our EXCLUSIVE Free class! 🚀

Get your hands dirty with lots of projects and labs based on Terraform and DevOps in our Program.
Click on the below image to Register for Our FREE Class Now!

Guide to Terraform's Plan and AWS VPC Creation Workflow (2024)
Top Articles
Understanding The Federal Funds Rate
How to Copyright Art
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 6192

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.