Skip to content

Latest commit

 

History

History
126 lines (84 loc) · 3.72 KB

LAB01-Terraform-Docker-Without-Cloud.md

File metadata and controls

126 lines (84 loc) · 3.72 KB

LAB-01: Terraform Docker => Pull Docker Image, Create Docker Container on Local Machine

This scenario shows:

  • how to use Terraform to manage Docker commands (image pull, container create, etc.)
  • without using any cloud, with Terraform Docker module, learning Terraform and making more practice could be easier.

Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/terraform-docker-without-cloud/main.tf

Prerequisite

Steps

  • Create main.tf and copy the code:
# main.tf
terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 3.0.2"
    }
  }
}

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

resource "docker_image" "windows" {
  name         = "mcr.microsoft.com/powershell:lts-windowsservercore-1809"
  keep_locally = true
}

# docker container run -p 80:8000 --name=tutorial -it mcr.microsoft.com/powershell:lts-windowsservercore-1809 powershell
resource "docker_container" "windows" {
  image = docker_image.windows.image_id
  name  = "tutorial"
  
  stdin_open = true             # docker run -i
  tty        = true             # docker run -t
  
  entrypoint = ["powershell"]
  
  ports {
    internal = 80
    external = 8000
  }
}

Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/terraform-docker-without-cloud/main.tf

image

  • Run init command:
terraform init

image

  • Validate file:
terraform validate
  • Run plan command:
terraform plan

image

  • Run apply command to create resources. Then, Terraform asks to confirm, write "yes":
terraform apply

image

  • With "docker container ls -a", running container is viewed:

image

  • Run following command to connect container powershell:
docker container exec -it tutorial powershell
  • Now, we are in the container, to prove it, we are looking at the users in the container (ContainerAdministrator, ContainerUser)

image

  • Before Terraform runs the container, it pulls the image:

image

  • When "keep_locally = true" in image part, image will be kept after terraform destroy.
terraform destroy

image

  • After destroy command, container is deleted, but image is still kept

image