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

There are lots of automation tools and scripts available for this and one of the finest tool to automate your infrastructure is Terraform which is also known as Infrastructure as code.

Learn how to Install and Setup Terraform on Windows Machine step by step.

Table of Content

  1. What is Terraform ?
  2. Prerequisites
  3. How to Install Terraform on Windows 10 machine
  4. Creating an IAM user in AWS account with programmatic access
  5. Configuring the IAM user Credentials on Windows Machine
  6. Run Terraform commands from Windows machine
  7. Launch a EC2 instance using Terraform
  8. Conclusion

What is Terraform ?

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

Terraform has been in use for quite a while now . I would say its an amazing tool to build , change the infrastructure in very effective and simpler way. It’s used with variety of cloud provider such as Amazon AWS, Oracle, Microsoft Azure , Google cloud and many more. I hope you would love to learn it and utilize it.

Prerequisites

How to Install Terraform on Windows machine

  • 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
  • Make a folder on your C:\ drive where you can put the Terraform executable something Like  C:\tools where you can put binaries.
  • Extract the zip file to the folder C:\tools
  • 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.
  • Now Under System Variables and look for Path and edit it
  • Click New and add the folder path where terraform.exe is located to the bottom of the list
  • Click OK on each of the menus.
  • Now, Open Command Prompt or PowerShell to check if terraform is properly added in PATH by running the command terraform from any location.
On Windows Machine command Prompt
On Windows Machine PowerShell
  • Verify the installation was successful by entering terraform --version. If it returns a version, you’re good to go.

Creating an IAM user in AWS account with programmatic access

For Terraform to connect to AWS Service, you should have an IAM user with an Access key ID and secret keys in the AWS account that you will configure on your local machine to connect to AWS account from your local machine.

There are two ways to connect to an AWS account, the first is providing a username and password on the AWS login page on the browser and the other way is to configure Access key ID and secret keys on your machine and then use command-line tools to connect programmatically.

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

Configuring the IAM user Credentials on Windows Machine

Now, you have an IAM user myuser created. The next, step is to set the download myuser credentials on the local machine which you will use to connect AWS service via API calls.

  1. Create a new file, C:\Users\your_profile\.aws\credentials on your local machine.
  2. Next, Enter the Access key ID and Secret access key from the downloaded csv file into the credentials file in the same format and save the file.
[default]     # Profile Name
aws_access_key_id = AKIAXXXXXXXXXXXXXXXX
aws_secret_access_key = vIaGXXXXXXXXXXXXXXXXXXXX

credentials files help you to set your profile. By this way, it helps you to create multiple profiles and avoid confusion while connecting to specific AWS accounts.

  1. Similarly, create another file C:\Users\your_profile\.aws\config in the same directory
  2. Next, add the “region” into the config file and make sure to add the name of the profile which you provided in the credentials file, and save the file. This file allows you to work with a specific region.
[default]   # Profile Name
region = us-east-2

Run Terraform commands from Windows machine

By Now , you have already installed Terraform on your windows Machine, Configured IAM user (myuser) credentials so that Terraform can use it and connect to AWS services in Amazon account.

Let us first understand terraform configuration files before running Terraform commands.

  • main.tf : This file contains code that create or import other AWS resources.
  • vars.tf : This file defines variable types and optionally set the values.
  • output.tf: This file helps in generating of the output of AWS resources .The output is generated after the terraform apply command is executed.
  • terraform.tfvars: This file contains the actual values of variables which we created in vars.tf
  • provider.tf: This file is very important . You need to provide the details of providers such as AWS , Oracle or Google etc. so that terraform can make the communication with the same provider and then work with resources.

Launch a EC2 Instance Using Terraform

In this demonstration we will create a simple Amazon Web Service (AWS) EC2 instance and run Terraform commands on Windows machine.

  • Create a folder on your desktop or any location on windows Machine ( I prefer it on Desktop)
  • Now create a file main.tf inside the folder you’re in and paste the below content
resource "aws_instance" "my-machine" {  # Resource block to define what 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 vars.tf inside the same folder and paste the below content
variable "ami" {         # Declare the variable ami which you used in main.tf
  type = string      
}

variable "instance_type" {        # Declare the variable instance_type used in main.tf
  type = string 
}

Next, selecting the instance type is important. Click here to see a list of different instance types. To find 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.

  • Create one more file output.tf inside the same folder and paste the below content
output "ec2_arn" {
  value = aws_instance.my-machine.arn     # Value depends on resource name and type ( same as that of main.tf)
}  
  • Create one more file provider.tf inside the same folder and paste the below content:
provider "aws" {      # Defining the Provider Amazon  as we need to run this on AWS   
  region = "us-east-1"
}
  • Create one more file terraform.tfvars inside the same folder and paste the below content
ami = "ami-013f17f36f8b1fefb" 
instance_type = "t2.micro"
  • Now your files and code are ready for execution .
  • Initialize the terraform using below command.
terraform init
  • Terraform initialized successfully , now its time to see the plan which is kind of blueprint before deployment. We generally use plan to confirm if correct resources is going to provisioned or deleted.
terraform plan
  • After verification , now its time to actually deploy the code using apply.
terraform apply
  • After verification , now its time to actually deploy the code using apply.
terraform apply

Great Job, terraform commands execution was done successfully. Now we should have ec2 instance launched in AWS.

It generally take a minute or so to launch a instance and yes we can see that the instance is successfully launched now in us-east-1 region as expected.

Conclusion

In this tutorial you learnt What is terraform , how to Install and Setup Terraform on Windows Machine and launched an ec2 instance on AWS account using terraform.

Keep Terraforming !!

Hope this tutorial will helps you in understanding and setting up Terraform on Windows machine. Please share with your friends.

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

Do you turn off off your lights when you leave your home or room ? Yes of course similarly when you don’t require any instance for sometime , its always a good practices to stop them and only start when required.

AWS EC2 is one of the most important and widely used service of Amazon where we launch instances. Many AWS accounts have almost multiple instance that are ideal and and requires some kind of automation to bring them either to stop state and when required power them on right away. Shell script works very well in automation world and for these activities . So Lets get started.

In this tutorial we will go through Shell script that takes few seconds to power on that is start or stop the instance.

Table of Content

  1. What is Shell script ?
  2. What is AWS EC2 instance?
  3. Prerequisites
  4. Install AWS CLI Version 2 on windows machine
  5. How to Start and Stop AWS EC2 instance in Amazon account using shell script
  6. Conclusion

What is Shell Scripting or Bash Scripting?

Shell Script is simply a text of file with various or lists of commands that are executed even on terminal or shell one by one. But in order to make thing little easier and run together as a group and in quick time we write them in single file and run it.

Main tasks which are performed by shell scripts are : file manipulation , printing text , program execution. We can include various environmental variables in script that can be used at multiple places , run programs and perform various activities are known as wrapper scripts.

A good shell script will have comments, preceded by a pound sign or hash mark, #, describing the steps. Also we can include conditions or pipe some commands to make more creative scripts.

When we 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 the top to the bottom.

What is AWS EC2 instance?

AWS EC2 stands for Amazon web service elastic compute cloud. AWS EC2 is just like a virtual server that is highly scalable in nature. The best part of EC2 instance is that, you don’t need to invest in any sort of hardware and it hardly takes few seconds to few minutes to launch. Once this is launched in few mins you are ready to deploy your applications. You can launch as many ec2 instance you wish to launch.

  • AWS EC2 service provides you Preconfigured templates known as AMI ( Amazon machine Image ) that includes operating system and software configurations that are highly required. Using these preconfigured templates you can launch your EC2 instances.
  • You can use Preconfigured templates and on the top of these templates you can configure your own software’s and data you wish to have when an instance is launched.
  • AWS EC2 service provides you various types of instance types with different CPU and Memory configurations. For Example: t2.micro, t2.medium etc.
  • AWS EC2 service provides login to these launched instances with completed security such as by creating a Key pair ( One of the key is public which remains with AWS and private is given the owner of instance)
  • AWS EC2 service allows you to add two kinds of storage . First storage is known as instance store volumes which are temporary storage and the other storage is EBS which is Elastic block storage & these are permanent storage.
  • Once AWS EC2 instance is launched you are the owner of the instance.
  • AWS EC2 is launched with root device volume that boots your system. You can have root device volumes as instance store based or as EBS based.
  • AWS EC2 service provides various states of a launched instance such as STOPPED , RUNNING , TERMINATED.
    • Note: Once instance is terminated it cannot be restarted back.

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. Python must be installed on windows machine which will be required by AWS cli. If you want to install python on windows machine follow here
  4. You must have Git bash already installed on your windows machine. If you don’t have install from here
  5. Code editor for writing the shell script on windows machine. I would recommend to use visual studio code on windows machine. If you wish to install visual studio on windows machine please find steps here

In this demo , we will use shell script to launch AWS IAM user. So In order to use shell scripts from your local machine that is windows you will require AWS CLI installed and configured. So First lets install AWS CLI and then configure it.

Install AWS CLI Version 2 on windows machine

  • Download the installed for AWS CLI on windows machine from here
  • Select I accept the terms and then click next button
  • Do custom setup like location of installation and then click next button
  • Now you are ready to install the AWS CLI 2
  • Click finish and now verify the AWS cli
  • Verify the AWS version by going to command prompt and type
aws --version

Now AWS cli version 2 is successfully installed on windows machine, now its time to configure AWS credentials so that our shell script connects AWS account and execute commands.

  • Configure AWS Credentials by running the command on command prompt
aws configure
  • Enter the details such as AWS Access key , ID , region . You can skip the output format as default.
  • Check the location on your system C:\Users\YOUR_USER\.aws file to confirm the the AWS credentials
  • Now, you’re AWS credentials are configured successfully.

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

Now we have configured AWS cli on windows machine , its time to create our shell script to stop and start ec2 instance.

This is a demo tutorial so we will show only one instance that will start if instance state is stopped and will stop it if its in running state.

  • Create a folder on your desktop and under that create file start-stop-ec2.sh
# /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
  • Now open visual studio code and open the location of file start-stop-ec2.sh and choose terminal as Bash
  • Now run the script
./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script
  • Script ran successfully , now lets verify the if EC2 instance has been stopped from running state by going on AWS account.
  • Great , Instance has been successfully stopped. Lets Now ,re- run the script to restart the instance
./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script

Conclusion

In this tutorial, we demonstrated what is  Amazon EC2 and learnt 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 it for AWS EC2 instances

Hope this tutorial will help you in understanding the shell script and working with AWS EC2 on Amazon cloud. Please share with your friends