云原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

时间:2022-09-21 19:56:59

前言

工欲善其事,必先利其器。本篇文章我们介绍下 Terraform,为后续创建各种云资源做准备,比如Kubernetes

 

关键词:IaC, Infrastructure as Code, Terraform, 基础架构即代码,Terraform 例子, Terraform 入门,Terraform 简介

 

Terraform 是什么?

Terraform 是一种安全有效地构建、更改和版本控制基础设施的工具(基础架构自动化的编排工具)。它的目标是 "Write, Plan, and create Infrastructure as Code", 基础架构即代码。Terraform 几乎可以支持所有市面上能见到的云服务。具体的说就是可以用代码来管理维护 IT 资源,把之前需要手动操作的一部分任务通过程序来自动化的完成,这样的做的结果非常明显:高效、不易出错。

Terraform 绝对是一个非常好用的工具,目前各大云平台也都支持的不错,我很看好它的未来。Terraform 也是用 Go 语言开发的开源项目,你可以在 github *问到它的源代码以及各种文档。

 

安装

我这里强烈推荐tfenv, 下面介绍如何在Mac上利用 tfenv 来安装Terraform。

安装 tfenv

brew install tfenv

brew link tfenv

利用tfenv 安装 Terraform

# install latest version
tfenv install latest

# install specific version
tfenv install 1.2.9

列出所有版本

% tfenv list                                                                                                
  1.2.9
  1.0.0
  0.14.2
  0.13.7
* 0.13.5 (set by /usr/local/Cellar/tfenv/2.0.0/version)

* 表示当前使用的版本

切换版本 

# switch to 1.2.9
tfenv use 1.2.9

Switching default version to v1.2.9
Switching completed

卸载

tfenv uninstall 0.14.2

tfenv uninstall latest

 ###  https://www.cnblogs.com/wade-xu/p/16709133.html ###

 

Provider

我们公司主要用GCP 谷歌云, 所以这里也用 google 的 provider 来入门Terraform

安装 Google Cloud SDK Install https://cloud.google.com/sdk/docs/quickstarts

Configure the environment for gcloud:

gcloud auth login

gcloud auth list

云原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

确保你的账号有权限操作GCP的Project

 

我的目录结构如下

云原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

 

providers.tf

 1 terraform {
 2   required_version = ">= 1.2.9"
 3 
 4   required_providers {
 5     google = {
 6       source  = "hashicorp/google"
 7       version = "~> 4"
 8     }
 9   }
10 }
11 
12 provider "google" {
13   project = local.project.project_id
14   region  = local.project.region
15 }

backend.tf

terraform {
  backend "gcs" {
    bucket = "wadexu007"
    prefix = "demo/state"
  }
}

这里的bucket要提前建好用来存放Terraform state文件。

 

network.tf

resource "google_compute_network" "default" {
  project                 = local.project.project_id
  name                    = local.project.network_name
  auto_create_subnetworks = true
  routing_mode            = "GLOBAL"
}

Network资源各个参数参考官方文档

 

locals.tf

locals {
  # project details
  project = {
    project_id       = "demo-eng-cn-dev"
    region           = "asia-east2"
    network_name     = "wade-test-network"
  }
}

 ###  https://www.cnblogs.com/wade-xu/p/16709133.html ###

 

init

在此目录下执行

terraform init

云原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

此目录下会生成 .terraform 文件夹,init其实就安装依赖插件到 .terraform 目录中:

 

Plan

plan 命令会检查配置文件并生成执行计划,如果发现配置文件中有错误会报错。

terraform plan

结果如下

 % terraform plan
Acquiring state lock. This may take a few moments...

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:

  # google_compute_network.default will be created
  + resource "google_compute_network" "default" {
      + auto_create_subnetworks         = true
      + delete_default_routes_on_create = false
      + gateway_ipv4                    = (known after apply)
      + id                              = (known after apply)
      + internal_ipv6_range             = (known after apply)
      + mtu                             = (known after apply)
      + name                            = "wade-test-network"
      + project                         = "xperiences-eng-cn-dev"
      + routing_mode                    = "GLOBAL"
      + self_link                       = (known after apply)
    }

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

 

Apply

在使用 apply 命令执行实际的部署时,默认会先执行 plan 命令并进入交互模式等待用户确认操作。

terraform apply

云原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

输入 Yes

云原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

Tips: 可以使用 -auto-approve 选项跳过这些步骤直接执行部署操作。

terraform apply -auto-approve

 

GCS bucket 里面的 Terraform 状态文件  gs://wadexu007/demo/state/default.tfstate 如下

{
  "version": 4,
  "terraform_version": "1.2.9",
  "serial": 1,
  "lineage": "30210d18-6dd5-a542-5b0d-xxxxxxxx",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "google_compute_network",
      "name": "default",
      "provider": "provider[\"registry.terraform.io/hashicorp/google\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "auto_create_subnetworks": true,
            "delete_default_routes_on_create": false,
            "description": "",
            "enable_ula_internal_ipv6": false,
            "gateway_ipv4": "",
            "id": "projects/demo-eng-cn-dev/global/networks/wade-test-network",
            "internal_ipv6_range": "",
            "mtu": 0,
            "name": "wade-test-network",
            "project": "demo-eng-cn-dev",
            "routing_mode": "GLOBAL",
            "self_link": "https://www.googleapis.com/compute/v1/projects/demo-eng-cn-dev/global/networks/wade-test-network",
            "timeouts": null
          },
          "sensitive_attributes": [],
          "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2xxxxxxxxxxxxxxxxxxxxx9"
        }
      ]
    }
  ]
}

GCP控制台查看新建的资源

云原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

 

Destory

terraform destroy 

销毁资源,务必小心

% terraform destroy 
Acquiring state lock. This may take a few moments...
google_compute_network.default: Refreshing state... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network]

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

Terraform will perform the following actions:

  # google_compute_network.default will be destroyed
  - resource "google_compute_network" "default" {
      - auto_create_subnetworks         = true -> null
      - delete_default_routes_on_create = false -> null
      - enable_ula_internal_ipv6        = false -> null
      - id                              = "projects/demo-eng-cn-dev/global/networks/wade-test-network" -> null
      - mtu                             = 0 -> null
      - name                            = "wade-test-network" -> null
      - project                         = "demo-eng-cn-dev" -> null
      - routing_mode                    = "GLOBAL" -> null
      - self_link                       = "https://www.googleapis.com/compute/v1/projects/demo-eng-cn-dev/global/networks/wade-test-network" -> null
    }

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

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

google_compute_network.default: Destroying... [id=projects/xperiences-eng-cn-dev/global/networks/wade-test-network]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 10s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 20s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 30s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 40s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 50s elapsed]
google_compute_network.default: Destruction complete after 54s
Releasing state lock. This may take a few moments...

Destroy complete! Resources: 1 destroyed.

 

附上我的learning by doing 代码 供参考。

 

总结

Terraform 用法很简单,支持的云厂商也很多,只要查看对应文档创建你的资源就行, 上述例子仅仅入门,玩法很多,还可以module化,这样不同的环境只需要source一下module,传入不同的参数就行。

除了建云资源,其它比如 Jenkins,Spinnaker, DNS,Vault 都可以用Terraform来建,所有infra 用代码来实现,人管代码,代码管基础设施,避免管理员直接控制台操作基础设施,后面再运用上Atlantis 将Terraform 在Git上运行,所有change走PR, review之后apply change, 这也是GitOps的一种最佳实践。

另外,Terraform 也支持开发自己的provider。


感谢阅读,如果您觉得本文的内容对您的学习有所帮助,您可以打赏和推荐,您的鼓励是我创作的动力。