How to Install and Setup Terraform on Windows Machine step by step

Are you new to Cloud, if yes then consider learning the most widely used open-source tool to automate your infrastructure using Terraform the Infrastructure as a code tool?

In this tutorial, you’ll learn how to Install and set up Terraform on Windows Machine step by step.

Let’s dive into it

Join 46 other followers

Table of Content

  1. What is Terraform ?
  2. Prerequisites
  3. How to Install Terraform on a Windows machine
  4. Creating an IAM user in AWS account with programmatic access
  5. Configure AWS credentials using aws configure
  6. Verify aws configure from AWS CLI by running a simple commands
  7. Creating AWS EC2 Instance Using Terraform
  8. Conclusion

What is Terraform?

Terraform is a tool for building, versioning, and changing the infrastructure. Terraform is Written in GO Language, and the syntax language of configuration files is HashiCorp configuration language(HCL) which is much easier than yaml or json.

Terraform is used with various cloud providers such as Amazon AWS, Oracle, Microsoft Azure, Google Cloud, etc.

Prerequisites

  • Any Windows Machine should work but this tutorial will use Windows 10 Machine.
  • Notepad or Notepad ++ or Visual Studio code editor on your windows Machine to create terraform configuration files. To install visual code studio click here.

Related: How to Install Terraform on an Ubuntu machine

How to Install Terraform on a Windows machine

Now that you have a basic idea about terraform let’s kick off this tutorial by first installing terraform on a Windows machine.

  • First open your favorite browser and download the appropriate version of Terraform from HashiCorp’s download Page. This tutorial will download terraform 0.13.0 version but you will find latest versions on the Hashicorps download page.
Downloading Terraform from Hashicorp website
Downloading Terraform from Hashicorp website
  • Make a folder on your C:\ drive where you can put the Terraform executable something Like  C:\tools where you can put binaries.
Downloading Terraform binary on the local machine
Downloading Terraform binary on the local machine
  • Extract the zip file to the folder C:\tools
Extracting the Terraform binary executable
Extracting the Terraform binary executable
  • Now Open your Start Menu and type in “environment” and the first thing that comes up should be Edit the System Environment Variables option. Click on that and you should see this window.
Editing the System Environment Variables option.
Editing the System Environment Variables option.
  • Now under System variables look for Path and edit it.
Editing the Path with Terraform binary location
Editing the Path with Terraform binary location
  • Click New and add the folder path where terraform.exe is located to the bottom of the list. By adding the terraform.exe in PATH will allow you to execute terraform command from anywhere in the system.
Updating the Windows Path with Terraform binary location
Updating the Windows Path with Terraform binary location
  • Click OK on each of the menus and further open command prompt or PowerShell to check if terraform is properly added in PATH by running the command terraform from any location.
Terraform command on command Prompt in Windows Machine
Terraform command on command Prompt in Windows Machine
Terraform command on PowerShell in Windows Machine
Terraform command on PowerShell in Windows Machine
  • Verify the installation was successful by entering terraform --version. If it returns a version, you’re good to go.
Running the terraform --version command
Running the terraform –version command

Creating an IAM user in AWS account with programmatic access

There are two ways to connect to an AWS account, the first is providing a username and password on the AWS login page and another is configuring the Access key ID and secret keys of IAM users in AWS CLI to connect programmatically.

Earlier, you installed AWS CLI successfully on a Windows machine, but you will need an IAM user with programmatic access to run commands from it.

Let’s learn how to create an IAM user in an AWS account with programmatic access, Access key ID, and secret keys.

  1. Open your favorite web browser and navigate to the AWS Management Console and log in.
  2. While in the Console, click on the search bar at the top, search for ‘IAM’, and click on the IAM menu item.
Checking the IAM AWS service
Checking the IAM AWS service
  1. To Create a user click on Users→ Add user and provide the name of the user myuser and make sure to tick the Programmatic access checkbox in Access type which enables an access key ID and secret access key and then hit the Permissions button.
Adding the IAM user in AWS CLoud
Adding the IAM user in AWS CLoud
  1. Now select the “Attach existing policies directly” option in the set permissions and look for the “Administrator” policy using filter policies in the search box. This policy will allow myuser to have full access to AWS services.
Attaching the admin rights to IAM user in AWS CLoud
Attaching the admin rights to IAM users in AWS CLoud
  1. Finally click on Create user.
  2. Now, the user is created successfully and you will see an option to download a .csv file. Download this file which contains IAM users i.e. myuser Access key ID and Secret access key which you will use later in the tutorial to connect to AWS service from your local machine.
Downloading the AWS credentials of IAM user
Downloading the AWS credentials of IAM user

Configure AWS credentials using aws configure in AWS CLI

You are an IAM user with Access key ID and secret keys, but AWS CLI cannot perform anything unless you configure AWS credentials. Once you configure the credentials, AWS CLI allows you to connect to the AWS account and execute commands.

  • Configure AWS Credentials by running the aws configure command on command prompt.
aws configure
  • Enter the details such as AWS Access key ID, Secret Access Key, region. You can skip the output format as default or text or json .
Configure AWS CLI using aws configure command
Configure AWS CLI using aws configure command
  • Once AWS is configured successfully , verify by navigating to C:\Users\YOUR_USER\.aws  and see if two file credentials and config are present.
Checking the credentials file and config on your machine
Checking the credentials file and config on your machine
  • Now open both the files and verify and you can see below you’re AWS credentials are configured successfully using aws configure.
Checking the config file on your machine
Checking the config file on your machine
Checking the config file on your machine
Checking the config file on your machine

Verify aws configure from AWS CLI by running a simple commands

Now, you can test if AWS Access key ID, Secret Access Key, region you configured in AWS CLI is working fine by going to command prompt and running the following commands.

aws ec2 describe-instances
Describing the AWS EC2 instances using AWS CLI
Describing the AWS EC2 instances using AWS CLI
  • You can also verify the AWS CLI by listing the buckets in your acount by running the below command.
aws cli s3

Creating AWS EC2 Instance Using Terraform

In this demonstration, you will learn how to create Amazon Web Service (AWS) EC2 instance using Terraform commands on a Windows machine. Lets dive in.

  • First, create a folder Terraform-EC2-simple-demo on your desktop or any location on Windows Machine.
  • Now create a file main.tf inside the folder you’re in and copy/paste the below content.
resource "aws_instance" "my-machine" {          # This is Resource block where we define what we need to create

  ami = var.ami                                 # ami is required as we need ami in order to create an instance
  instance_type = var.instance_type             # Similarly we need instance_type
}
  • Create one more file named vars.tf file under Terraform-EC2-simple-demo folder and copy/paste the content below. The vars.tf file contains the variables that you referred in main.tf file.
variable "ami" {                       # We are declaring the variable ami here which we used in main.tf
  type = string      
}

variable "instance_type" {             # We are declaring the variable instance_type here which we used in main.tf
  type = string 
}

To select the the image ID ( ami ), navigate to the LaunchInstanceWizard and search for ubuntu in the search box to get all the ubuntu image IDs. This tutorial will use Ubuntu Server 18.04.LTS image.

Choosing the Amazon Machine Image
Choosing the Amazon Machine Image
  • Create one more file output.tf file under Terraform-EC2-simple-demomo folder and paste the content below. This file will allow Terraform to display he output after running terraform apply command.
output "ec2_arn" {
  value = aws_instance.my-machine.arn    
}  
  • Create provider.tf file under Terraform-EC2-simple-demo folder and paste the content below.
provider "aws" {     # Defining the Provider Amazon  as we need to run this on AWS  
  region = "us-east-2"
}
  • Create terraform.tfvars file under Terraform-EC2-simple-demo folder and paste the content below. This file contains the value of Terraform vaiables declared in vars.tf file.
ami = "ami-013f17f36f8b1fefb" 
instance_type = "t2.micro"
  • Now your files and code are ready for execution and the folder structure should look something like below.
 folder structure of terraform configuration files
folder structure of terraform configuration files
  • Now your files and code are ready for execution. Initialize the terraform using the terraform init command.
terraform init
Initializing the terraform using the terraform init command.
Initializing the terraform using the terraform init command.
  • Terraform initialized successfully , now its time to run the plan command which provides you the details of the deployment. Run terraform plan command to confirm if correct resources is going to provisioned or deleted.
terraform plan
Running the terraform plan command
Running the terraform plan command
  • After verification, now its time to actually deploy the code using terraform apply command.
terraform apply
Running the terraform apply command
Running the terraform apply command

Great Job; terraform commands were executed successfully. Now you should have the AWS EC2 instance launched in AWS Cloud.

Verifying the AWS instance
Verifying the AWS instance

Generally takes a minute or so to launch an instance, and yes, you can see that the instance is successfully launched now in the us-east-2 region as expected.

Conclusion

In this tutorial, you learned What is terraform, how to Install Terraform on the Windows machine and launch an ec2 instance on an AWS account using terraform.

Now that you have the AWS EC2 instance launched, what are you planning to deploy next using Terraform?

How to Start and Stop AWS EC2 instance in AWS account using Shell script

Are you spending unnecessary money in AWS Cloud by keeping unused AWS EC2 instances in running states? Why not stop the AWS EC2 instance and only start when required by running a single Shell Script?

Multiple AWS accounts contain dozens of AWS EC2 instances that require some form of automation to stop or start these instances, and to achieve this, nothing could be better than running a shell script.

In this tutorial, you will learn step by step how to Start and Stop AWS EC2 instance in AWS account using Shell script.

Still interested? Let’s dive in!

Join 46 other followers

Table of Content

  1. What is Shell Scripting or Bash Scripting?
  2. What is AWS EC2 instance?
  3. Prerequisites
  4. Building a shell script to start and stop AWS EC2 instance
  5. Executing the Shell Script to Stop AWS EC2 instance
  6. Verifying the Stopped AWS EC2 instance
  7. Executing the Shell Script to Start AWS EC2 instance
  8. Verifying the Running AWS EC2 instance
  9. Conclusion

What is Shell Scripting or Bash Scripting?

Shell Script is a text file containing lists of commands executed on the terminal or shell in one go in sequential order. Shell Script performs various important tasks such as file manipulation, printing text, program execution.

Shell script includes various environmental variables, comments, conditions, pipe commands, functions, etc., to make it more dynamic.

When you execute a shell script or function, a command interpreter goes through the ASCII text line-by-line, loop-by-loop, test-by-test, and executes each statement as each line is reached from top to bottom.

What is AWS EC2 instance?

AWS EC2 stands for Amazon web service elastic compute cloud. AWS EC2 is simply a virtual server that gets launched in quick time, and you don’t need to worry about the hardware. After the AWS EC2 instance is launched, you can deploy highly scalable and available applications.

There are some important components in AWS EC2 instance such as:

AWS EC2 AMI

  • AWS EC2 contains preconfigured templates known as AMI ( Amazon Machine Image ) that include an operating system and software configurations that are highly required. Using these preconfigured templates you can launch as many AWS EC2 instances.

You can configure your own software’s and data you wish to have when an instance on top of Preconfigured templates.

Amazon Machine Image template
Amazon Machine Image template

AWS EC2 instance type

AWS EC2 contains various AWS EC2 instance types with different CPU and memory configurations such as t2.micro, t2.medium, etc.

AWS EC2 instance type
AWS EC2 instance type

Amazon EC2 key pairs

AWS EC2 instance allows you to log in to these launched instances with complete security by creating a Keypair where one of the keys is public that remains within the AWS account, and another is the private key that remains with the owner of the instance.

AWS EC2 EBS Storage

AWS EC2 allows you to add two kinds of storage that is ec2 instance store volumes which are temporary storage, and Elastic block storage (AWS EBS), the permanent storage.

AWS EC2 is launched with root device volume ( ec2 instance store volumes or AWS EBS ) that allows you to boot the machine.

AWS EC2 EBS Storage
AWS EC2 EBS Storage

AWS EC2 instance state

AWS EC2 service provides various states of a launched instance such as stopped, started, running, terminated. Once the instance is terminated, it cannot be restarted back.

AWS EC2 instance state
AWS EC2 instance state

Prerequisites

  1. AWS account to create ec2 instance. If you don’t have AWS account please create from AWS account or AWS Account
  2. Windows 7 or plus edition where you will execute the shell script.
  3. AWS CLI installed. To install AWS CLI click here.
  4. Git bash. Yo install Git bash click here
  5. Code editor for writing the shell script on windows machine such as visual studio code. To install visual studio click here.

Building a shell script to start and stop AWS EC2 instance

Now that you have a good idea about the AWS EC2 instance and shell script but let’s learn how to build a shell script to start and stop the AWS EC2 instances.

  • Create a folder of your windows machine at any location. Further under the same folder create a file named start-stop-ec2.sh and copy/paste the below code.
# /usr/bin/bash 

set -e  # set -e stops the execution of a script if a command or pipeline has an error

id=$1   # Provide the instance ID with the name of the script

# Checking if Instance ID provided is correct 

function check_ec2_instance_id () {
    
    if echo "$1" | grep -E '^i-[a-zA-Z0-9]{8,}' > /dev/null; then 
           echo "Correct Instance ID provided , thank you"
           return 0
    else 
          echo "Opps !! Incorrect Instance ID provided !!"
          return 1
    fi
}

# Function to Start the instance 

function ec2_start_instance ()   {
     aws ec2 start-instances --instance-ids $1 
}

# Function to Stop the instance 

function ec2_stop_instance ()   {
     aws ec2 stop-instances --instance-ids $1 
}

# Function to Check the Status of the instance

function ec2_check_status ()   {
     aws ec2 describe-instances --instance-ids $1 --query "Reservations[].Instances[].State.Name" --output text
}

# Main Function 

function main ()  {
     check_ec2_instance_id $1                # First it checks the Instance ID
     echo " Instance ID provided is $1"  # Prints the message
     echo "Checking the status of $1"    # Prints the message
     ec2_check_status $1
                 # Checks the Status of Instance
   
     status=$(ec2_check_status $id)     # It stores the status of Instance
     if [ "$status" = "running" ]; then     
         echo "I am stopping the instance now"
         ec2_stop_instance $1
         echo "Instance has been stopped successfully"
     else 
         echo "I am starting the instance now"
         ec2_start_instance $1
         echo "Instance has been Started successfully" 
     fi

}

main $1                                 # Actual Script starts from main function

Executing the Shell Script to Stop AWS EC2 instance

Previously you created the shell script to start and stop the AWS EC2 instance, which is great; but it is not doing much unless you run it. Let’s execute the shell script now.

  • Open the visual studio code and then open the location of file start-stop-ec2.sh.
Opening Shell script on visual studio code
Opening Shell script on visual studio code
  • Finally execute the shell script.
./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script
Executing the shell script to stop the AWS Ec2 instance
Executing the shell script to stop the AWS Ec2 instance

Verifying the Stopped AWS EC2 instance

Earlier in the previous section, the shell script ran successfully; let’s verify the if AWS EC2 instance has been stopped from running state in the AWS account.

  • Open your favorite web browser and navigate to the AWS Management Console and log in.
  • While in the Console, click on the search bar at the top, search for ‘EC2’, and click on the EC2 menu item and you should see the instance you specified in shell script has stopped now.
Viewing the stopped AWS EC2 instance
Viewing the stopped AWS EC2 instance

Executing the Shell Script to Start AWS EC2 instance

Now thaYouuccessfully stopped and verified the AWS EC2 instance in the AWS cloud. This time let’s restart the instance using the same script.

./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script
Executing the shell script to start the instance
Executing the shell script to start the instance

Verifying the Running AWS EC2 instance

Similarly, in this section, let’s verify the if AWS EC2 instance has been restarted successfully in the AWS account.

Viewing the running AWS EC2 instance
Viewing the running AWS EC2 instance

Conclusion

In this tutorial, you learned what is Amazon EC2 and learned how to start or stop AWS EC2 using shell script on AWS step by step. It is always a good practice to turn off your lights when you leave your home or room, similarly do for EC2 instances.

So which AWS EC2 instance are you planning to stop going further and save dollars?