欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Terraform入门教程,示例展示管理Docker和Kubernetes资源

程序员文章站 2022-07-01 23:36:27
我最新最全的文章都在 南瓜慢说 www.pkslow.com ,欢迎大家来喝茶! 1 简介 最近工作中用到了Terraform,权当学习记录一下,希望能帮助到其它人。 Terraform系列文章如下: Terraform入门教程,示例展示管理Docker和Kubernetes资源 Terraform ......

我最新最全的文章都在,欢迎大家来喝茶!

1 简介

最近工作中用到了terraform,权当学习记录一下,希望能帮助到其它人。

terraform系列文章如下:

terraform入门教程,示例展示管理docker和kubernetes资源

terraform插件provider管理,搜索、定义、下载

terraform状态state管理,让变更有记录

terraform模块module管理,聚合资源的抽取与复用

terraform常用命令

terraform是一个可快速部署、方便管理it基础架构配置的工具,它的理念是infrastructure as code,一切资源都是代码。如虚拟机、网络、dns等,这些都通过代码来管理部署,而不是人工手动的去创建、删除等。它能大大减少人为操作的风险,能快速部署多套环境,适应多种硬件资源,特别适合云环境:aws、gcp、azure、阿里云等。

它通过丰富的providers来管理多种类型的资源,就像是插件一样,如gcp、docker、kubernetes等。

本文将通过演示讲解如何部署docker/kubernetes资源。

Terraform入门教程,示例展示管理Docker和Kubernetes资源

2 安装

到官方对应的二进制文件,我通过命令操作,我选择的是mac的版本:

# 创建目录
$ mkdir terraform
$ cd terraform/
# 下载安装包
$ wget https://releases.hashicorp.com/terraform/0.15.4/terraform_0.15.4_darwin_amd64.zip
# 解压
$ unzip terraform_0.15.4_darwin_amd64.zip
# 查看版本,显示安装成功
$ ./terraform --version
terraform v0.15.4
on darwin_amd64

成功显示了版本,我们把它添加到环境变量中去即可。

3 部署docker资源

创建个目录:

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

创建一个main.tf文件,写入以下内容:

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
  }
}

根据main.tf初始化项目:

$ 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.

我们先执行plan来看看它将会有什么变更:

$ 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.

执行变更:

$ 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]

它自动帮我们下载了镜像和启动了容器。通过以下命令查看nginx的主页:

$ curl http://localhost:8000

现在我不想要这些资源了,通过以下命令删除:

$ 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 部署kubernetes资源

创建目录:

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

创建main.tf文件:

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
    }
  }
}

直接执行:

terraform init
terraform apply

检查结果:

$ 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

测试完成,删除:

terraform destroy

5 总结

terraform在云计算领域还是有自己的一席之地的,值得了解学习。

代码请查看:https://github.com/larrydpk/pkslow-samples


欢迎关注微信公众号<南瓜慢说>,将持续为你更新...

Terraform入门教程,示例展示管理Docker和Kubernetes资源

多读书,多分享;多写作,多整理。