【GCP和Terraform】【入门篇①】使用Terraform创建GCP虚拟机

Terraform 是什麼?

请参考以下资料,这是由HashiCorp用Go语言开发的Iac(Infrastructure as Code)工具,可以通过代码来构建云上基础设施。

以下是一个中文本地化的用心服务的链接选项:

https://www.lac.co.jp/lacwatch/service/20200903_002270.html

这次我打算使用 Terraform 来创建 Google Cloud 上的虚拟机。关于 GCP 的基本操作和 Terraform 的概念解释我会省略不提。

■议程

    1. 在GCP上使用Terraform创建实例配置文件.tf

 

    执行示例

Terraform在GCP上的应用

Terraform已预装在Cloud Shell中。
打开Cloud Shell,确认Terraform可以使用。

terraform

帮助打印

Usage: terraform [global options] <subcommand> [args]

The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.

Main commands:
  init          Prepare your working directory for other commands
  validate      Check whether the configuration is valid
  plan          Show changes required by the current configuration
  apply         Create or update infrastructure
  destroy       Destroy previously-created infrastructure

All other commands:
  console       Try Terraform expressions at an interactive command prompt
  fmt           Reformat your configuration in the standard style
  force-unlock  Release a stuck lock on the current workspace
  get           Install or upgrade remote Terraform modules
  graph         Generate a Graphviz graph of the steps in an operation
  import        Associate existing infrastructure with a Terraform resource
  login         Obtain and save credentials for a remote host
  logout        Remove locally-stored credentials for a remote host
  output        Show output values from your root module
  providers     Show the providers required for this configuration
  refresh       Update the state to match remote systems
  show          Show the current state or a saved plan
  state         Advanced state management
  taint         Mark a resource instance as not fully functional
  test          Experimental support for module integration testing
  untaint       Remove the 'tainted' state from a resource instance
  version       Show the current Terraform version
  workspace     Workspace management

Global options (use these before the subcommand, if any):
  -chdir=DIR    Switch to a different working directory before executing the
                given subcommand.
  -help         Show this help output, or the help for a specified subcommand.
  -version      An alias for the "version" subcommand.

创建一个名为”構成文件.tf”的文件。

让我们启动一个VM实例。有关配置文件格式,请查看此文档。

请点击以下链接访问 terraform.io 的官方网站,了解有关 Terraform 语言的更多信息。

配置文件的扩展名是.tf(.tf.json)。

创建一个名为instance.tf的空配置文件。

touch instance.tf

使用命令或云端Shell的编辑器来编辑已创建的配置文件。

nano instance.tf

请将以下内容添加到文件中,并将其替换为Google Cloud项目ID。

resource "google_compute_instance" "terraform" {
  project      = "<PROJECT_ID>"
  name         = "tf-instance"
  machine_type = "n1-standard-1"
  zone         = "asia-northeast1-c"
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }
  network_interface {
    network = "default"
    access_config {
    }
  }
}

以下是简单的解释:
“resource”块用于定义基础设施中存在的资源。
在打开块之前,有两个字符串:资源类型和资源名称。资源类型是google_compute_instance,资源名称是terraform。类型前缀与提供程序对应,因此输入google_compute_instance,Terraform会自动识别为由Google提供程序管理的资源。
块的内容是在控制台上创建虚拟机时的参数。

使用ls命令来确认目录中不包含其他*.tf文件。这是因为Terraform会读取所有*.tf文件。

执行示例

1. 初期化
对于新配置(或者从版本控制中检出的现有配置),首先要执行的命令是terraform init。执行该命令后,将初始化用于之后命令中使用的各种本地设置和本地数据。

terraform init

对于”出力例”的本地化解释:
– 实例输出
– 输出样例
– 示例输出
– 出力案例

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/google...
- Installing hashicorp/google v4.21.0...
- Installed hashicorp/google v4.21.0 (signed by HashiCorp)

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.

执行计划创建
执行此命令将更新执行计划。然后,根据配置文件指定的操作确定达到所需状态所需的操作。
该命令可方便地在预期状态中,通过应用一系列更改的执行计划,而无需更改实际资源和状态来确认是否可以实现预期目标。

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.terraform will be created
  + resource "google_compute_instance" "terraform" {
      + can_ip_forward       = false
      + cpu_platform         = (known after apply)
      + current_status       = (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         = "n1-standard-1"
      + metadata_fingerprint = (known after apply)
      + min_cpu_platform     = (known after apply)
      + name                 = "tf-instance"
      + project              = "<PROJECT_ID>"
      + self_link            = (known after apply)
      + tags_fingerprint     = (known after apply)
      + zone                 = "asia-northeast1-c"

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

      + confidential_instance_config {
          + enable_confidential_compute = (known after apply)
        }

      + network_interface {
          + ipv6_access_type   = (known after apply)
          + name               = (known after apply)
          + network            = "default"
          + network_ip         = (known after apply)
          + stack_type         = (known after apply)
          + subnetwork         = (known after apply)
          + subnetwork_project = (known after apply)

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

      + reservation_affinity {
          + type = (known after apply)

          + specific_reservation {
              + key    = (known after apply)
              + values = (known after apply)
            }
        }

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

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

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

执行计划中描述了用于根据此配置更改实际基础架构的操作。输出的格式类似于通过Git等工具生成的差异格式。

在与instance.tf文件相同的目录中执行以下命令:应用更改。

terraform apply

如果计划成功创建,则 Terraform 会在此处暂停,并在继续之前请求批准。

Enter a value: 

在这个例子中,由于计划没有问题,所以请在确认提示中输入“yes”以继续执行。
执行计划可能需要几分钟时间,因为 Terraform 需要等待 VM 实例可用。

出力例的中文翻译:输出示例

.......

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

google_compute_instance.terraform: Creating...
google_compute_instance.terraform: Still creating... [10s elapsed]
google_compute_instance.terraform: Creation complete after 14s [id=projects/<project-id>/zones/asia-northeast1-c/instances/tf-instance]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

到目前为止,实例的创建已经完成,并且可以在控制台上进行确认。
要更改已经创建的资源,请先修改其对应的配置文件.tf,
然后执行terraform apply即可进行更改。

4.确认现状
在云Shell上确认当前状态。

terraform show

出力实例 lì)

# google_compute_instance.terraform:
resource "google_compute_instance" "terraform" {
    can_ip_forward       = false
    cpu_platform         = "Intel Broadwell"
    current_status       = "RUNNING"
    deletion_protection  = false
    enable_display       = false
    guest_accelerator    = []
    id                   = "projects/<project-id>/zones/asia-northeast1-c/instances/tf-instance"
    instance_id          = "4562989540648335002"
    label_fingerprint    = "42WmSpB8rSM="
    machine_type         = "n1-standard-1"
    metadata_fingerprint = "3DFjFhfX0U8="
    name                 = "tf-instance"
......
    zone                 = "asia-northeast1-c"
......
}

5. 删除创建的实例
通过以下命令,可以删除由terraform构建的所有资源。

terraform destroy

产量示例

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_instance.terraform will be destroyed
......
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_instance.terraform: Destroying... [id=projects/<project-id>/zones/asia-northeast1-c/instances/tf-instance]
google_compute_instance.terraform: Still destroying... [id=projects/<project-id>/zon...sia-northeast1-c/instances/tf-instance, 10s elapsed]
google_compute_instance.terraform: Still destroying... [id=projects/<project-id>/zon...sia-northeast1-c/instances/tf-instance, 20s elapsed]
google_compute_instance.terraform: Destruction complete after 22s

Destroy complete! Resources: 1 destroyed.

最终

我希望从下次开始按照以下的顺序进行介绍。

    1. Terraform的依赖关系和VPC的配置,

 

    1. Terraform模块的操作,

 

    Terraform State的管理。
广告
将在 10 秒后关闭
bannerAds