尝试进入Terraform的入门级别

Terraform是什么?

哈希科技(Hashicorp)正在开发的开源基础架构自动化构建工具。
可以将基础架构资源以代码方式定义,并根据代码构建资源。

将基础设施资源以代码形式定义的过程称为基础设施即代码(IaC)。除了Terraform之外,还有以下类似的IaC工具。

ツール名管理対象対応コード定義AWS Cloud Formationマネージドサービス全般の構成AWSYAMLAzure Resource Managerマネージドサービス全般の構成AzureJSONDeployment Managerマネージドサービス全般の構成GCPYAML等Serverless Frameworkサーバレスサービス全般の構成AWS
Azure
GCP
Alibaba Cloud ​YAML

Terraform的执行顺序。

与npm和bundler类似。

    1. 编写Terraform文件

 

    1. 通过terraform init进行初始化

 

    1. 检查执行结果并修改文件

 

    1. 实际执行并构建基础设施

 

    如果需要更改,编辑文件并重新执行

管理文件

使用以.tf为扩展名的文件进行管理。

terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
      version = "3.5.0"
    }
  }
}

provider "google" {
  credentials = file("<NAME>.json")

  project = "<PROJECT_ID>"
  region  = "us-central1"
  zone    = "us-central1-c"
}

resource "google_compute_network" "vpc_network" {
  name = "terraform-network"
}

土地改造

terraform块用于描述terraform本身的配置。可以指定依赖库的版本和管理元数据的状态文件的存放位置。

提供者

描述与AWS和GCP等服务通信所需的设置,例如区域和认证信息。

资源

可以使用形如resource “资源名称” “变量名称”的语法来指定要构建的基础设施的配置,并且可以使用变量来引用该资源的内容。

用Terraform来管理GCP资源的试验

1. 安装

从官方网站上下载并安装Terraform的CLI。
从这里下载二进制文件并解压。

请确认安装。

$ terraform --version
Terraform v1.0.11

2. 要做的事情 zuò de

使用VPC在GCP上建立一个私有网络,并在网络中创建实例。

3. 资源的创建 de

在查看有关GCP的文档时,逐步创建tf文件。

terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "3.5.0"
    }
  }
}

provider "google" {
  credentials = file(var.credentials_file)

  project = var.project
  region  = var.region
  zone    = var.zone
}

resource "google_compute_network" "vpc_network" {
  name = "terraform-network"
}

resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "f1-micro"

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }

  network_interface {
    network = google_compute_network.vpc_network.name
    access_config {
    }
  }
}
variable "project" {
  default = "<your project name>"
}

variable "credentials_file" {
  default = "<your path to service account json file>"
}

variable "region" {
  default = "us-central1"
}

variable "zone" {
  default = "us-central1-c"
}

进行初始化

执行以下命令。

$ terraform init

在与文件相同的目录中将创建以下目录/文件:
.terraform
.terraform.lock.hcl

确认

执行以下命令。

$ terraform plan

如果文件的语法或帐户权限存在错误,它会在这里为您进行检查。

如果出现错误
$ terraform plan
╷
│ Error: Unsupported attribute
│ 
│   on main.tf line 13, in provider "google":
│   13:   project     = "${lookup(var.project_name.tf_sample, "${terraform.workspace}")}"
│     ├────────────────
│     │ var.project_name is object with 1 attribute "tf-sample"
│ 
│ This object does not have an attribute named "tf_sample".
╵
╷
│ Error: error archiving directory: could not archive missing directory: ./../src
│ 
│   with data.archive_file.function_zip,
│   on main.tf line 42, in data "archive_file" "function_zip":
│   42: data "archive_file" "function_zip" {
│ 
╵
如果成功的话
$ 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:

  # google_compute_instance.vm_instance will be created
  + resource "google_compute_instance" "vm_instance" {
      + can_ip_forward       = false
      + cpu_platform         = (known after apply)
      + deletion_protection  = false
      + guest_accelerator    = (known after apply)
      + id                   = (known after apply)
      + instance_id          = (known after apply)
      + label_fingerprint    = (known after apply)
      + machine_type         = "f1-micro"
      + metadata_fingerprint = (known after apply)
      + min_cpu_platform     = (known after apply)
      + name                 = "terraform-instance"
      + project              = (known after apply)
      + self_link            = (known after apply)
      + tags_fingerprint     = (known after apply)
      + zone                 = (known after apply)

      + boot_disk {
          + auto_delete                = true
          + device_name                = (known after apply)
          + disk_encryption_key_sha256 = (known after apply)
          + kms_key_self_link          = (known after apply)
          + mode                       = "READ_WRITE"
          + source                     = (known after apply)

          + initialize_params {
              + image  = "debian-cloud/debian-9"
              + labels = (known after apply)
              + size   = (known after apply)
              + type   = (known after apply)
            }
        }

      + network_interface {
          + name               = (known after apply)
          + network            = "terraform-network"
          + network_ip         = (known after apply)
          + subnetwork         = (known after apply)
          + subnetwork_project = (known after apply)

          + access_config {
              + nat_ip       = (known after apply)
              + network_tier = (known after apply)
            }
        }

      + scheduling {
          + automatic_restart   = (known after apply)
          + on_host_maintenance = (known after apply)
          + preemptible         = (known after apply)

          + node_affinities {
              + key      = (known after apply)
              + operator = (known after apply)
              + values   = (known after apply)
            }
        }
    }

  # google_compute_network.vpc_network will be created
  + resource "google_compute_network" "vpc_network" {
      + auto_create_subnetworks         = true
      + delete_default_routes_on_create = false
      + gateway_ipv4                    = (known after apply)
      + id                              = (known after apply)
      + ipv4_range                      = (known after apply)
      + name                            = "terraform-network"
      + project                         = (known after apply)
      + routing_mode                    = (known after apply)
      + self_link                       = (known after apply)
    }

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

执行

执行以下命令。

$ terraform apply
スクリーンショット 2021-11-16 午後11.21.25.png
vm show.png

如果您想要进行更改,您可以通过应用更改文件来更改资源。

删掉 chú)

执行以下命令。

$ terraform destroy

已创建的资源被删除。

留意事项

只能管理基础架构的配置。
无法管理服务账号的设置和API的启用等。

广告
将在 10 秒后关闭
bannerAds