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
- You should have a look following lab:
- Install Docker on your system.
- 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
- Run init command:
terraform init
- Validate file:
terraform validate
- Run plan command:
terraform plan
- Run apply command to create resources. Then, Terraform asks to confirm, write "yes":
terraform apply
- With "docker container ls -a", running container is viewed:
- 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)
- Before Terraform runs the container, it pulls the image:
- When "keep_locally = true" in image part, image will be kept after terraform destroy.
terraform destroy
- After destroy command, container is deleted, but image is still kept
- With Terraform, we can manage docker images, containers..
- More information: https://registry.terraform.io/providers/kreuzwerker/docker/latest/docs/resources/container