Terraform needs to be told which provider to be used in the automation, hence we need to give the provider name with source and version. For Docker, we can use this block of code in your main. tf
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 2.21.0"
}
}
}
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" {}
https://registry.terraform.io/providers/hashicorp/aws/latest
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-02
- 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.latest
name = "tutorial"
ports {
internal = 80
external = 80
}
}
Connect to the instance and install docker using the below commands
$ sudo apt-get update
$ sudo apt install
docker.io
$ sudo docker ps
$ sudo chown $USER /var/run/docker.sock
Create a main.tf because terraform file should have a .tf extension
Put provider and resources in the main.tf
Now we will use terraform commands to build and run an nginx webserver
$ terraform init
$ terraform plan
$ terraform validate
$ terraform fmt
$ terraform apply
Our nginx webserver is built and run from a Image and now it is containerized