How to work with multiple Terraform Provisioners

Have you ever worked with passing the data or any script on any compute resource after they are created successfully ? Most of you might have worked with passing the user data or scripts at the time of creation.

You have come to right place to learn about latest and most widely used terraform provisoners which solves the problem of working with data after resource is created or already existing data.

Table of content

  1. What is Terraform provisioners
  2. What are different actions performed by terraform provisioners.
  3. Prerequisites
  4. How to Install Terraform on Ubuntu 18.04 LTS
  5. Terraform Configuration Files and Structure
  6. Working with Various terraform provisioners on AWS EC2 instance
  7. Conclusion

What is Terraform provisioners?

Most cloud computing platforms provide different ways to pass data into instances such as ec2 instance or any other compute resource at the time of their creation so that the data is immediately available on system boot. This is possible with various code functions such as by passing user_data . Also at the time of creating the EC2 instance AMI’s we can pass the data.

But what if we need to provide the data after resource is created or already in place? Here comes role of terraform provisioner which passes the data after resource is created or for existed resources.

There are lots of terraform provisioners that interact with remote servers over SSH or WinRM can be used to pass such data by logging in to the server and providing it directly.

What are different actions performed by terraform provisioners.

  1. They perform specific action on local machine that means they generate output on same machine
  2. They perform specific action on remote machine that means they generate output on remote machine
  3. They perform specific action on to copy files remotely on machines.
  4. These are used to enter or pass data in any resource which cannot be passed at the time of creation of resources.
  5. You can have conditions in provisioner such as when = destroy , on_failure = continue

Prerequisites

  • Ubuntu machine to run terraform preferably 18.04 version + , if you don’t have any machine you can create a ec2 instance on AWS account
  • Recommended to have 4GB RAM
  • At least 5GB of drive space
  • Ubuntu machine should have IAM role attached with all EC2 permissions or it is always great to have administrator permissions to work with demo’s.

You may incur a small charge for creating an EC2 instance on Amazon Managed Web Service.

How to Install Terraform on Ubuntu 18.04 LTS

  • Update your already existing system packages.
sudo apt update
  • Download the latest version of terraform in opt directory
wget https://releases.hashicorp.com/terraform/0.14.8/terraform_0.14.8_linux_amd64.zip
This image has an empty alt attribute; its file name is image-163.png
  • Install zip package which will be required to unzip
sudo apt-get install zip -y
  • unzip the Terraform download zip file
unzip terraform*.zip
  • Move the executable to executable directory
sudo mv terraform /usr/local/bin
  • Verify the terraform by checking terraform command and version of terraform
terraform               # To check if terraform is installed 

terraform -version      # To check the terraform version  
This image has an empty alt attribute; its file name is image-164.png
This image has an empty alt attribute; its file name is image-165.png
  • This confirms that terraform has been successfully installed on ubuntu 18.04 machine.

Terraform Configuration Files and Structure

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.

Working with Various terraform provisioners on AWS EC2 instance

Now, lets dive into demo where you will use multiple provisioners . This tutorial will Create a secret key pair ( Public and Private keys) so that provisioners uses to connect and login to machine over SSH protocol . Using local exec provisioners executes command locally on the machine. Next, remote exec provisioners installs software on AWS EC2 instance and finally File Provisioners upload the file in the ec2 instance

  • Create a file main.tf and paste the below code.
resource "aws_key_pair" "deployer" {     # Creating the Key pair on AWS 
  key_name   = "deployer-key"
  public_key = "${file("~/.ssh/id_rsa.pub")}" # Generated private and public key on local machine
}
 
resource "aws_instance" "my-machine" {        # Creating the instance
 
  ami = "ami-0a91cd140a1fc148a"
  key_name = aws_key_pair.deployer.key_name
  instance_type = "t2.micro"
 
  provisioner  "local-exec" {                  # Provisioner 1
        command = "echo ${aws_instance.my-machine.private_ip} >> ip.txt"
        on_failure = continue
       }
 
  provisioner  "remote-exec" {            # Provisioner 2 [needs SSH/Winrm connection]
      connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("~/.ssh/id_rsa")}"
      agent       = false
      host        = aws_instance.my-machine.public_ip       # Using my instance to connect
      timeout     = "30s"
    }
      inline = [
        "sudo apt install -y apache2",
      ]
  }
 
  provisioner "file" {                    # Provisioner 3 [needs SSH/Winrm connection]
    source      = "C:\\Users\\4014566\\Desktop\\service-policy.json"
    destination = "/tmp/file.json"
    connection {
      type        = "ssh"
      user        = "ubuntu"
      host        = aws_instance.my-machine.public_ip
      private_key = "${file("~/.ssh/id_rsa")}"
      agent       = false
      timeout     = "30s"
    }
  }  
  • Create a file provider.tf and paste the below code
provider "aws" {
  region = "us-east-2"
}
  • Now your files and code are ready for execution . Initialize the terraform
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 plan verification , run the apply command to deploy the code.
terraform apply
  • Lets now verify the commands and execution.
command executed locally on the ubuntu machine using local exec
command executed on remote machine using other remote-exec and file provisioners

Great Job, Terraform commands execution was done successfully locally and on remote machine in AWS.

Conclusion

In this tutorial, we demonstrated some benefits of terraform provisioners and learnt how to work with various terraform provisioners using terraform on AWS step by step .

Hope this tutorial will help you in understanding the terraform and working with various terraform provisioners on Amazon cloud. Please share with your friends

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s