Day 62 - Terraform and Docker

Day 62 - Terraform and Docker

Day 62 of 90daysofdevops

Task 1

  • Create a Terraform script with Blocks and Resources

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

Note: kreuzwerker/docker, is shorthand for registry.terraform.io/kreuzwerker/docker.

Provider Block

The provider block configures the specified provider, in this case, docker. A provider is a plugin that Terraform uses to create and manage your resources.

provider "docker" {}

Resource

Use resource blocks to define components of your infrastructure. A resource might be a physical or virtual component such as a Docker container, or it can be a logical resource such as a Heroku application.

Resource blocks have two strings before the block: the resource type and the resource name. In this example, the first resource type is docker_image and the name is Nginx.

Task 2

  • Create a resource Block for an nginx docker image

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

  • Create a resource Block for running a docker container for Nginx

      resource "docker_container" "nginx" {
       image = docker_image.nginx.name
       name  = "tutorial"
       ports {
         internal = 80
         external = 81
       }
      }
    

    Note: In case Docker is not installed

    sudo apt-get install docker.io
    sudo docker ps
    sudo chown $USER /var/run/docker.sock

  • Now the terraform configuration file is created, So we will initialize the terraform using the terraform init command.

  • Run terrafrom validate to validate the files.

  • Run the terraform plan command to see the execution plan of Terraform configuration.

  • Apply the Terraform configuration to create and start the Docker container.

  • After Terraform completes, we can verify that the Docker container is running by checking the Docker processes.

Thank you for reading!!
~Shreya Gupta

Great initiative by the #trainwithshubham community. Thank you Shubham Londhe

#devops #90daysofdevops #terraform