mac平台使用Terraform创建Docker 应用

Author: Ju4t

安装 terraform

Centos 安装

$ sudo yum install -y yum-utils
$ sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
$ sudo yum -y install terraform

Mac 安装

$ brew tap hashicorp/tap
$ brew install hashicorp/tap/terraform

配置 terraform

# main.tf
terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 2.15.0"
    }
  }
}

provider "docker" {
  host = "unix:///var/run/docker.sock"
}

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

resource "docker_container" "nginx" {
  image = docker_image.nginx.name
  name  = var.container_name
  ports {
    internal = 80
    # external = 8000
    external = 8080
  }
}


# variables.tf
variable "container_name" {
  description = "Value of the name for the Docker container"
  type        = string
  default     = "MyNginx"
}


# outputs.tf
output "container_id" {
  description = "ID of the Docker container"
  value       = docker_container.nginx.id
}

output "image_id" {
  description = "ID of the Docker image"
  value       = docker_image.nginx.id
}

应用

# 初始化,安装插件
$ terraform init

# 格式化并验证配置
$ terraform fmt
$ terraform validate
# 执行计划
$ terraform plan

# 应用
$ terraform apply [yes]
# 指定var
$ terraform apply -var "container_name=Nginx"

# 删除
$ terraform destroy

# 手动管理状态
$ terraform state list

# 输出内容
$ terraform output

https://developer.hashicorp.com/terraform/tutorials/docker-get-started/install-cl