Terraform DevOps using Jenkins Part1:Getting started with Terraform

Godfrey Menezes
4 min readAug 27, 2021

Terraform has been a blessing for cloud adoption since the last couple of years. Allied to DevOps, it can be a powerful tool that helps automate the IaC(Infrastructure as Code). Here I will take a shot at my recent learning experience in getting started and then using it with Jenkins for automated code deployment.

Setting up your machine for TerraForm

To get started, download the binary to run terraform on your machine from here. I’m using Windows 10, so I chose the Windows 64 bit option. Create a folder with the executable to store the binary -

Setup the environment path with the executable so that it can be invoked. This can be done by invoking the Start -> Run -> env command and setting it in the path variable ->

This should help you run the TerraForm command from your command prompt -

Setting up AWS Free Tier Account

For the brevity of article, will refrain from how to sign up and create an AWS Account. Additionally to configure TerraForm to interact and create resources, we will need to setup environment variables. Create the credentials for your account as shown below -

This will create 2 values, the access key id and the secret access key. These keys will be used to interact with the account. To configure the credentials, install the AWS cli and create a credentials file in the user’s .aws folder. Something like this —

The contents of the file should be something like this. Please change it to reflect your credentials —

[default]
region=us-east-2
aws_access_key_id = AKIAUGRYK4OKWWNK****
aws_secret_access_key = VhTDee2iEes74dRjOwJmoaCAq44SyqUB********

Creating a TerraForm script to create AWS resources

Now that we have our environment setup, the first course of action is to make sure that you can run a TerraForm script. In this case I’m using a simple script that just specifies the provider I’m going to use -

provider "aws" {
region = "us-east-2"
}

From the directory that contains this main.tf file run the commands to test terraform.

terraform init
terraform plan
terraform apply

Successful running with result that will look something similar -

Now that we have terraform running, lets create an actual resource-in this case a EC2 instance-in AWS.

provider "aws" {
region = "us-east-2"
}

resource "aws_instance" "example"{
ami = "ami-028f0daffc74d96ee"
instance_type = "t2.micro"
}

Run the ‘terraform plan’ command and it will output with an ending something like this -

Run the terraform apply plan to create the EC2 instance-

Type yes and press enter to continue with creation of the resource -

Make a note of the id and check the EC2 panel to find the matching instance id. That means it has been created successfully.

Destroy the EC2 instance to not incur any further charges using the command terraform destroy,

--

--