DEV Community

Albert Jokelin
Albert Jokelin

Posted on

Terraform pt-2

Hey Reader-
Just started learning terraform and this articles serves to explain what I have learnt. If you have any thoughts or feel that I may be wrong, do let me know. My plan for this is to make this a series of articles that can explain the tool from my POV.

Cheers
A


Contents

  1. Intro to terraform
  2. Terraform pt-2

In this post, we will discuss how to install and use terraform on your PC.

Installation

First, we head over to the Terraform downloads page and choose the operating system we want to download Terraform for.

Installation page

If you're downloading for Windows like I did, then there are a couple of steps you must follow:

  1. Download, unzip and place the terraform binary somewhere you wouldn't accidentally delete it.
  2. Add the location to your system PATH variable. Check out this guide for https://stackoverflow.com/questions/1618280/where-can-i-set-path-to-make-exe-on-windows.
  3. Verify the installation by running terraform -help. You should be getting this:

Terraform help response

Quick start

Let's try using Terraform with an Nginx server and understand how it works.

Before we go ahead, install Docker on your PC. If you're on windows, you will need WSL 2 to run docker.

We're gonna be referencing the guide here.

Let's start off by making a working directory:

mkdir myTerraformDir
cd myTerraformDir 
Enter fullscreen mode Exit fullscreen mode

We're gonna create a file called main.tf and paste the following code into it.

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 3.0.1"
    }
  }
}

provider "docker" {
  host    = "npipe:////.//pipe//docker_engine"
}

resource "docker_image" "nginx" {
  name         = "nginx"
  keep_locally = false
}

resource "docker_container" "nginx" {
  image = docker_image.nginx.image_id
  name  = "tutorial"

  ports {
    internal = 80
    external = 8000
  }
}
Enter fullscreen mode Exit fullscreen mode

Once you're done, save the file and run terraform init. This is the output you'll get on Windows.

terraform init response

And then you run terraform plan which give you the following output:

Terraform plan response

Run terraform apply and head over to localhost:8000, this is what you'll find:

Nginx server

And if you run docker ps, this is what you'll get:

Image description

To shut this down, run terraform destroy.

Image description

Voila! you've made and destroyed your first server with terraform. In the following guides, we're gonna explore how to use terraform with AWS.

References:

  1. https://developer.hashicorp.com/terraform/downloads?product_intent=terraform
  2. https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli
  3. https://spacelift.io/blog/terraform-tutorial

Top comments (0)