使用terraform在Windows终端上生成GCP实例

首先

因为开始接触GCP,知道了Terraform的存在,所以尝试使用了一下。

改造地球

以下是一个选项的汉语表达:
https://www.terraform.io/intro/index.html 是一款用于管理基础架构构建的工具。

安装Terraform

这次,我要在我的Windows 7设备上进行安装。
不过,只需要下载二进制文件即可。

image.png

目前的版本为0.11.7

image.png

下载64位的Windows版
解压下载的zip文件

经解压后,以下为可执行文件 terraform.exe。

创建一个合适的文件夹并将其内容存储其中。

GCP的前期准备工作

1:创建新项目
2:创建服务账号
[IAM和管理]→[服务账号]
[创建服务账号]
※勾选提供新的密钥
密钥类型为JSON
3:将下载的JSON文件存放在先前创建的文件夹中。

tf文件准备

TF文件是用于通过terraform构建基础设施的配置文件,在根据不同的角色将文件分割后,可以通用地进行操作。

首先,创建以下的tf文件以传递GCP的连接信息。

// GCP provider
provider "google" {
  credentials = "${file("key\\XXXXXXXXXX.json")}"
  project     = "XXXXXXX-999999"
  region      = "us-east1"
}

・credentials代表GCP认证键文件路径。如下所述,使用相对路径引用存放在key文件夹下的JSON文件,需要转义反斜杠\。
・project是认证键文件中所记载的[project_id]★请注意,无法使用GCP控制台上显示的项目名称,这点让我困扰了一阵。。。

为了创建下一个实例所用的tf文件

这次我们将为了Terraform验证,仅在GCP上创建一个简单实例。

resource "google_compute_instance" "terraform-test" {
  name         = "terraform-test"
  machine_type = "f1-micro"
  zone         = "us-east1-c"
  description  = "gcp-terraform-test"
  tags         = ["terraform-test"]
  boot_disk {
    initialize_params {
      image = "XXXXXXXXXXXXXXXX"
    }
  }
  network_interface {
    network = "default"
    access_config {
      // Ephemeral IP
    }
  }
  service_account {
    scopes = ["userinfo-email", "compute-ro", "storage-ro", "monitoring"]
  }
}

・启动磁盘 – 初始化参数 – 可根据喜好选择镜像
本次使用了之前创建的CentOS 7的类似lamp的镜像。

文件夹结构

terraform/
├ terraform.exe
├ key/
│ └ XXXXXXXXXX.json
└ gcp/
├ gcp_provider.tf
└ gcp_instances.tf

terraform/
├ terraform执行文件
├ 密钥/
│ └ XXXXXXXXXX.json
└ gcp/
├ gcp提供者配置文件.tf
└ gcp实例配置文件.tf

执行Terraform

启动命令提示符

进入目标文件夹
terraform 初始化 GCP

terraform 计划 GCP

terraform 应用 GCP

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

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-test: Still creating... (10s elapsed)
google_compute_instance.terraform-test: Creation complete after 13s (ID: terraform-test)

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

从GCP控制台确认,已经启动了创建的实例。

最后

虽然在 project_id 上遇到了困难,耗费了大约3个小时,但最终顺利完成了。接下来要使用 Ansible。

广告
将在 10 秒后关闭
bannerAds