Terraform introductory tutorial with examples showing managing Docker and Kubernetes resources

1 Introduction

TerraformIt is a tool for rapid deployment and easy management of IT infrastructure [configuration] . Its philosophy is Infrastructure as Codethat all resources are code. Such as [virtual machines] , networks, DNS, etc., these are managed and deployed through code, instead of manually creating, deleting, etc. It can greatly reduce the risk of human operation, can quickly deploy multiple environments, adapt to a variety of hardware resources, and is especially suitable for cloud environments: AWS, GCP, Azure, Alibaba Cloud, etc.

It manages multiple types of resources Providersthrough , just like plugins, such as GCP, [Docker] , Kubernetes, etc.

This article will demonstrate how to deploy Docker/ [Kubernetes] resources.

2 Installation

Go to the official download interface corresponding to the binary file, I operate through the command, I choose the Mac version:

# Create a directory
$ mkdir terraform
$ cd terraform/
# Download the installation package 
$ wget https://releases.hashicorp.com/terraform /0.15.4/terraform _ 0 . 15.4_ darwin_amd64.zip # Unzip 
$ unzip terraform_ 0 . 15.4_ darwin_amd64.zip
 #
 Check the version and show that the installation is successful
$ ./terraform --version
Terraform v0.15.4
on darwin_amd64

The version is successfully displayed, we can add it to the environment variable.

3 Deploy Docker resources

Create a directory:

$ mkdir terraform-docker-demo && cd $_

Create a main.tffile with the following content:

terraform {
  required_providers {
    docker = {
      source = "kreuzwerker/docker"
    }
  }
}

provider "docker" {}

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

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

According to the main.tfinitialization project:

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of kreuzwerker/docker...
- Installing kreuzwerker/docker v2.12.2...
- Installed kreuzwerker/docker v2.12.2 (self-signed, key ID 24E54F214569A8A5)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Let’s execute the plan first to see what changes it will have:

$ terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # docker_container.nginx will be created
  + resource "docker_container" "nginx" {
      + attach           = false
      + bridge           = (known after apply)
      + command          = (known after apply)
      + container_logs   = (known after apply)
      + entrypoint       = (known after apply)
      + env              = (known after apply)
      + exit_code        = (known after apply)
      + gateway          = (known after apply)
      + hostname         = (known after apply)
      + id               = (known after apply)
      + image            = (known after apply)
      + init             = (known after apply)
      + ip_address       = (known after apply)
      + ip_prefix_length = (known after apply)
      + ipc_mode         = (known after apply)
      + log_driver       = "json-file"
      + logs             = false
      + must_run         = true
      + name             = "tutorial"
      + network_data     = (known after apply)
      + read_only        = false
      + remove_volumes   = true
      + restart          = "no"
      + rm               = false
      + security_opts    = (known after apply)
      + shm_size         = (known after apply)
      + start            = true
      + stdin_open       = false
      + tty              = false

      + healthcheck {
          + interval     = (known after apply)
          + retries      = (known after apply)
          + start_period = (known after apply)
          + test         = (known after apply)
          + timeout      = (known after apply)
        }

      + labels {
          + label = (known after apply)
          + value = (known after apply)
        }

      + ports {
          + external = 8000
          + internal = 80
          + ip       = "0.0.0.0"
          + protocol = "tcp"
        }
    }

  # docker_image.nginx will be created
  + resource "docker_image" "nginx" {
      + id           = (known after apply)
      + keep_locally = false
      + latest       = (known after apply)
      + name         = "nginx:latest"
      + output       = (known after apply)
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Execute the change:

$ terraform apply
docker_image.nginx: Creating...
docker_image.nginx: Still creating... [10s elapsed]
docker_image.nginx: Still creating... [20s elapsed]
docker_image.nginx: Creation complete after 28s [id=sha256:d1a364dc548d5357f0da3268c888e1971bbdb957ee3f028fe7194f1d61c6fdeenginx:latest]
docker_container.nginx: Creating...
docker_container.nginx: Creation complete after 1s [id=0dac86e383366959bd976cc843c88395a17c5734d729f62f07106caf604b466f]

It automatically downloaded the image and started the container for us. View the homepage of nginx with the following command:

$ curl http://localhost:8000

Now I don’t want these resources anymore, delete them with the following command:

$ terraform destroy
docker_container.nginx: Destroying... [id=0dac86e383366959bd976cc843c88395a17c5734d729f62f07106caf604b466f]
docker_container.nginx: Destruction complete after 0s
docker_image.nginx: Destroying... [id=sha256:d1a364dc548d5357f0da3268c888e1971bbdb957ee3f028fe7194f1d61c6fdeenginx:latest]
docker_image.nginx: Destruction complete after 1s

4 Deploy Kubernetes resources

Create a directory:

$ mkdir terraform-kubernetes-demo && cd $_

Create main.tffile :

terraform {
  required_providers {
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = ">= 2.0.0"
    }
  }
}
provider "kubernetes" {
  config_path = "~/.kube/config"
}
resource "kubernetes_namespace" "test" {
  metadata {
    name = "nginx"
  }
}
resource "kubernetes_deployment" "test" {
  metadata {
    name      = "nginx"
    namespace = kubernetes_namespace.test.metadata.0.name
  }
  spec {
    replicas = 2
    selector {
      match_labels = {
        app = "MyTestApp"
      }
    }
    template {
      metadata {
        labels = {
          app = "MyTestApp"
        }
      }
      spec {
        container {
          image = "nginx"
          name  = "nginx-container"
          port {
            container_port = 80
          }
        }
      }
    }
  }
}
resource "kubernetes_service" "test" {
  metadata {
    name      = "nginx"
    namespace = kubernetes_namespace.test.metadata.0.name
  }
  spec {
    selector = {
      app = kubernetes_deployment.test.spec.0.template.0.metadata.0.labels.app
    }
    type = "NodePort"
    port {
      node_port   = 30201
      port        = 80
      target_port = 80
    }
  }
}

Execute directly:

terraform init
terraform apply

test result:

$ kubectl -n nginx get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   2/2     2            2           2m

$ kubectl -n nginx get service
NAME    TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
nginx   NodePort   10.98.213.164   <none>        80:30201/TCP   71s

$ curl http://localhost:30201

Test done, delete:

terraform destroy

5 Summary

TerraformThere is still a place in the field of cloud computing, which is worth learning about.

Leave a Comment

Your email address will not be published. Required fields are marked *