如何与团队一起使用 Terraform

作者选择了 自由和开源基金作为 写给捐款计划的一部分接受捐款。

介绍

当多个人同时从不同的位置工作在同一 Terraform 项目上时,重要的是正确处理基础设施代码和项目状态,以避免重写错误。

其中一个远程后端是 pg,它将状态存储在 PostgreSQL 数据库中. 在本教程的过程中,您将与 DigitalOcean Managed Database一起使用,以确保数据可用性。

Terraform 还支持 Hashicorp 官方的管理云服务,名为 Terraform Cloud - 一个专有应用程序,可在一个地方同步您的团队的工作,并为配置和管理提供用户界面。

在本教程中,你将创建一个组织在Terraform Cloud中,你将连接你的项目,然后使用你的组织来设置工作空间和资源,你将存储你的状态在管理云中,以便它始终可用。

前提条件

您可以通过DigitalOcean控制面板创建一个DigitalOcean个人访问代币。 您可以在DigitalOcean产品文档中找到指示(如何创建个人访问代币)(https://docs.digitalocean.com/reference/api/create-personal-access-token/)。 *在本地机器上安装了Terraform。 完成DigitalOcean控制面板(https://andsky.com/tech/tutorials/how-to-use-terraform-with-digitalocean)教程 的 步骤1。 如果您想使用pg后端,您需要创建并可访问的Managed PostgreSQL(https://www.digitalocean.com/docs/databases/postgresql/)数据库群集。 有关更多信息,请访问Quickstart指南(https://www.digitalocean.com/docs/databases/postgresql/quickstart/)。 您可以使用本教程的单独数据库

  • 如果您想要使用Hashicorp的管理云,

<$>[注] **注:**我们使用Terraform 1.1.3 进行了专门的测试。

在管理 PostgreSQL 数据库中存储状态

在本节中,您将设置一个项目,该项目部署Droplet并使用pg提供商将状态存储在DigitalOcean Managed PostgreSQL数据库中。

首先,创建一个名为terraform-team-pg的目录,您将存储该项目:

1mkdir ~/terraform-team-pg

导航它:

1cd ~/terraform-team-pg

您首先将定义提供商,然后传输数据库和digitalocean模块的连接字符串。

1nano provider.tf

添加以下几行:

 1[label ~/terraform-team-pg/provider.tf]
 2terraform {
 3  required_providers {
 4    digitalocean = {
 5      source = "digitalocean/digitalocean"
 6      version = "~> 2.0"
 7    }
 8  }
 9
10  backend "pg" {
11    conn_str = "your_db_connection_string"
12  }
13}
14
15variable "do_token" {}
16
17provider "digitalocean" {
18  token = var.do_token
19}

在这里,您需要digitalocean提供商,并定义pg后端,它接受连接字符串,然后,您定义do_token变量,并将其传递给digitalocean提供商的实例。

请记住,在您的 DigitalOcean 控制面板中将your_db_connection_string替换为您管理的数据库的连接字符串,您可以通过点击 Actions,选择 Connection Details,并从下滑菜单中选择 Connection string来找到它。

<$>[警告] 警告: 要继续,在您的数据库的 设置,请确保您在允许列表中运行 Terraform 的机器的 IP 地址。

通过运行开始项目:

1terraform init

结果将类似于以下:

 1[secondary_label Output]
 2Initializing the backend...
 3
 4Successfully configured the backend "pg"! Terraform will automatically
 5use this backend unless the backend configuration changes.
 6
 7Initializing provider plugins...
 8- Finding digitalocean/digitalocean versions matching "~> 2.0"...
 9- Installing digitalocean/digitalocean v2.16.0...
10- Installed digitalocean/digitalocean v2.16.0 (signed by a HashiCorp partner, key ID F82037E524B9C0E8)
11
12Partner and community providers are signed by their developers.
13If you'd like to know more about provider signing, you can read about it here:
14https://www.terraform.io/docs/cli/plugins/signing.html
15
16Terraform has created a lock file .terraform.lock.hcl to record the provider
17selections it made above. Include this file in your version control repository
18so that Terraform can guarantee to make the same selections by default when
19you run "terraform init" in the future.
20
21Terraform has been successfully initialized!
22...

Terraform成功初始化了后端,这意味着它连接到数据库。

接下来,在名为droplets.tf的文件中定义 Droplet。

1nano droplets.tf

添加以下几行:

1[label ~/terraform-team-pg/droplets.tf]
2resource "digitalocean_droplet" "web" {
3  image  = "ubuntu-20-04-x64"
4  name   = "web-1"
5  region = "fra1"
6  size   = "s-1vcpu-1gb"
7}

这个代码将部署一个名为web-1的Dropplet在fra1区域,运行Ubuntu 20.04在1GB RAM和一个CPU核心上。

你需要你的 DigitalOcean 代币在一个环境变量中。创建一个,用你的代币代替 your_do_token:

1export DO_PAT="your_do_token"

若要检查数据库连接是否正常运行,请尝试计划配置:

1terraform plan -var "do_token=${DO_PAT}"

结果将类似于以下:

 1[secondary_label Output]
 2Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
 3following symbols:
 4  + create
 5
 6Terraform will perform the following actions:
 7
 8  # digitalocean_droplet.web will be created
 9  + resource "digitalocean_droplet" "web" {
10      + backups              = false
11      + created_at           = (known after apply)
12      + disk                 = (known after apply)
13      + graceful_shutdown    = false
14      + id                   = (known after apply)
15      + image                = "ubuntu-20-04-x64"
16      + ipv4_address         = (known after apply)
17      + ipv4_address_private = (known after apply)
18      + ipv6                 = false
19      + ipv6_address         = (known after apply)
20      + locked               = (known after apply)
21      + memory               = (known after apply)
22      + monitoring           = false
23      + name                 = "web-1"
24      + price_hourly         = (known after apply)
25      + price_monthly        = (known after apply)
26      + private_networking   = (known after apply)
27      + region               = "fra1"
28      + resize_disk          = true
29      + size                 = "s-1vcpu-1gb"
30      + status               = (known after apply)
31      + urn                  = (known after apply)
32      + vcpus                = (known after apply)
33      + volume_ids           = (known after apply)
34      + vpc_uuid             = (known after apply)
35    }
36
37Plan: 1 to add, 0 to change, 0 to destroy.
38...

Terraform 报告没有错误,并像往常一样计划了操作。它成功连接到您的 PostgreSQL 数据库并存储了其状态。

在 Terraform 云中存储状态

在此步骤中,您将创建一个部署 Droplet 的项目,并使用 Terraform Cloud作为其与提供商的后端。

创建一个组织

Terraform Cloud 允许您拥有多个 organizations,以容纳您的工作空间和模块。有付费计划的组织可以拥有多个团队,具有访问级别控制功能,而您将使用的免费计划仅为每个组织提供一个团队。

首先,转到 Terraform Cloud并登录,如果您尚未创建组织,它将提示您这样做。

Terraform Cloud - Create a new organization

输入您选择的组织名称,并记住,它必须在 Terraform Cloud 中的所有名称中是唯一的。如果这个名称已经存在,您将收到错误消息。电子邮件地址应该已经填写您的帐户地址。

然后它会要求您选择工作空间的类型。

Terraform Cloud - Choosing a workspace type

由于您将使用命令行与 Terraform Cloud 进行交互,请单击 CLI 驱动工作流选项,然后输入您的工作区的名称,然后将描述留空。

Terraform Cloud - Setting workspace name

输入您选择的工作区名称(我们将称之为sammy),然后单击创建工作区以完成组织创建过程。

Terraform Cloud - Workspace settings

您现在已经创建了工作区,这是您组织的一部分,因为您刚刚创建了工作区,因此工作区不包含基础设施代码。

在连接到它之前,您需要配置云端将使用的Terraform版本来执行您的命令。 要设置它,请单击 Settings下载点,在 Overview旁边,并从列表中选择 ** General**。

Terraform Cloud - Setting Terraform Version

然后,点击保存设置按钮来保存更改。

要将您的项目连接到您的组织和工作区,您首先需要使用命令行登录。在运行命令之前,请导航到 tokens 页面为您的服务器创建一个新的访问令牌,该令牌将提供访问到您的帐户。

Terraform Cloud - Create API token

默认描述是好的,所以点击 Create API token 来创建它。

Terraform Cloud - Created API token

点击代币值或后面的图标来复制 API 代币. 您将使用此代币将您的项目连接到您的 Terraform Cloud 帐户。

在命令行中,运行以下命令登录:

1terraform login

您将收到以下输出:

 1[secondary_label Output]
 2Terraform will request an API token for app.terraform.io using your browser.
 3
 4If login is successful, Terraform will store the token in plain text in
 5the following file for use by subsequent commands:
 6    /home/sammy/.terraform.d/credentials.tfrc.json
 7
 8Do you want to proceed?
 9  Only 'yes' will be accepted to confirm.
10...

Terraform正在警告你,代币将被存储在本地。输入是的,当它提示你:

 1[secondary_label Output]
 2---------------------------------------------------------------------------------
 3
 4Open the following URL to access the tokens page for app.terraform.io:
 5    https://app.terraform.io/app/settings/tokens?source=terraform-login
 6
 7---------------------------------------------------------------------------------
 8
 9Generate a token using your browser, and copy-paste it into this prompt.
10
11Terraform will store the token in plain text in the following file
12for use by subsequent commands:
13    /home/sammy/.terraform.d/credentials.tfrc.json
14
15Token for app.terraform.io:
16  Enter a value:

粘贴您已复制的代币并用ENTER确认。

 1[secondary_label Output]
 2...
 3                                          -
 4                                          -----                           -
 5                                          ---------                      --
 6                                          ---------  -                -----
 7                                           ---------  ------        -------
 8                                             -------  ---------  ----------
 9                                                ----  ---------- ----------
10                                                  --  ---------- ----------
11   Welcome to Terraform Cloud!                     -  ---------- -------
12                                                      ---  ----- ---
13   Documentation: terraform.io/docs/cloud             --------   -
14                                                      ----------
15                                                      ----------
16                                                       ---------
17                                                           -----
18                                                               -
19
20   New to TFC? Follow these steps to instantly apply an example configuration:
21
22   $ git clone https://github.com/hashicorp/tfc-getting-started.git
23   $ cd tfc-getting-started
24   $ scripts/setup.sh

您已配置您的本地 Terraform 安装以访问您的 Terraform Cloud 帐户,您现在将创建一个部署 Droplet 的项目,并将其配置为使用 Terraform Cloud 来存储其状态。

创建项目

首先,创建一个名为terraform-team-cloud的目录,存储该项目:

1mkdir ~/terraform-team-cloud

导航它:

1cd ~/terraform-team-cloud

要创建你的项目,你需要:

  • 定义和配置与 Terraform Cloud 接口的提供商 *要求digitalocean提供商能够部署 DigitalOcean 资源 *定义和初始化您将使用的变量

您将存储提供商和模块要求规格在名为provider.tf的文件中。

1nano provider.tf

添加以下几行:

 1[label ~/terraform-team-cloud/provider.tf]
 2terraform {
 3  required_providers {
 4    digitalocean = {
 5      source = "digitalocean/digitalocean"
 6      version = "~> 2.0"
 7    }
 8  }
 9
10  cloud {
11    organization = "your_organization_name"
12
13    workspaces {
14      name = "your_workspace_name"
15    }
16  }
17}
18
19variable "do_token" {}
20
21provider "digitalocean" {
22  token = var.do_token
23}

在这里,您首先指定您的Terraform版本,然后根据需要指定digitalocean提供商,并将后端设置为cloud

接下来,您定义了一个名为do_token的变量,将其传递给之后创建的digitalocean提供商,您现在已经配置了您的项目以连接到您的组织,所以保存并关闭该文件。

用以下命令启动您的项目:

1terraform init

结果将类似于此:

 1[secondary_label Output]
 2Initializing Terraform Cloud...
 3
 4Initializing provider plugins...
 5- Finding digitalocean/digitalocean versions matching "~> 2.0"...
 6- Installing digitalocean/digitalocean v2.18.0...
 7- Installed digitalocean/digitalocean v2.18.0 (signed by a HashiCorp partner, key ID F82037E524B9C0E8)
 8
 9Partner and community providers are signed by their developers.
10If you'd like to know more about provider signing, you can read about it here:
11https://www.terraform.io/docs/cli/plugins/signing.html
12
13Terraform has created a lock file .terraform.lock.hcl to record the provider
14selections it made above. Include this file in your version control repository
15so that Terraform can guarantee to make the same selections by default when
16you run "terraform init" in the future.
17
18Terraform Cloud has been successfully initialized!
19...

由于 Droplet 定义与前一个项目相同,您可以通过运行来复制它:

1cp ../terraform-team-pg/droplets.tf .

最后,您将定义变量值。‘云’提供商不支持通过命令行将值传递给变量,因此您将不得不使用变量文件传输它们或在Terraform Cloud中设置它们。Terraform会从文件中读取变量值,其文件名结尾为‘.auto.tfvars’。创建并打开名为‘vars.auto.tfvars’的文件以进行编辑,在其中您将定义‘do_token’变量:

1nano vars.auto.tfvars

添加以下行,用您的 DigitalOcean API 代码取代 your_do_token:

1[label vars.auto.tfvars]
2do_token = "your_do_token"

完成后,保存并关闭文件 Terraform 会在计划操作时自动阅读此文件。

您的项目现在已经完成并设置为使用Terraform Cloud作为其后端,您现在将计划和应用Droplet,并审查它如何反映在云应用中。

应用配置

在本教程的 步骤 1中,您使用terraform 计划命令计划了一个项目. 由于 Terraform Cloud 项目具有相同的资源定义,您可以再次跳过计划,并直接应用到 Terraform Cloud。

您可以通过运行以下命令来应用该项目来更新它:

1terraform apply

您会注意到输出与使用本地作为后端不同:

 1[secondary_label Output]
 2Running apply in Terraform Cloud. Output will stream here. Pressing Ctrl-C
 3will cancel the remote apply if it's still pending. If the apply started it
 4will stop streaming the logs, but will not stop the apply running remotely.
 5
 6Preparing the remote apply...
 7
 8To view this run in a browser, visit:
 9https://app.terraform.io/app/sammy-shark/sammy/runs/run-euVu9t1yUtuq5sy9
10
11Waiting for the plan to start...
12
13Terraform v1.1.3
14on linux_amd64
15Configuring remote state backend...
16Initializing Terraform configuration...
17
18Terraform used the selected providers to generate the following execution
19plan. Resource actions are indicated with the following symbols:
20  + create
21
22Terraform will perform the following actions:
23
24  # digitalocean_droplet.web will be created
25  + resource "digitalocean_droplet" "web" {
26      + backups              = false
27      + created_at           = (known after apply)
28      + disk                 = (known after apply)
29      + graceful_shutdown    = false
30      + id                   = (known after apply)
31      + image                = "ubuntu-20-04-x64"
32      + ipv4_address         = (known after apply)
33      + ipv4_address_private = (known after apply)
34      + ipv6                 = false
35      + ipv6_address         = (known after apply)
36      + locked               = (known after apply)
37      + memory               = (known after apply)
38      + monitoring           = false
39      + name                 = "web-1"
40      + price_hourly         = (known after apply)
41      + price_monthly        = (known after apply)
42      + private_networking   = (known after apply)
43      + region               = "fra1"
44      + resize_disk          = true
45      + size                 = "s-1vcpu-1gb"
46      + status               = (known after apply)
47      + urn                  = (known after apply)
48      + vcpus                = (known after apply)
49      + volume_ids           = (known after apply)
50      + vpc_uuid             = (known after apply)
51    }
52
53Plan: 1 to add, 0 to change, 0 to destroy.
54...

在使用后端时,Terraform 不会从本地机器计划或应用配置,而是将这些任务转移到Terraform Cloud,并且只会实时向控制台流输出。

Terraform 将很快完成应用配置,您可以导航到 Terraform Cloud 网站上的工作区,以发现它已经应用了新的操作。

Terraform Cloud - New Run Applied

您现在可以通过执行以下操作来摧毁部署的资源:

1terraform destroy

在本节中,您已将项目连接到Terraform Cloud,使项目的状态可在中心位置访问您的团队,从而允许所有可以访问项目的人共享和同步该状态,从而实现更顺利的体验。

结论

在本教程中,您使用了两个不同的后端:Terraform Cloud,这是Hashicorp的Terraform管理云提供;和pg,允许您在PostgreSQL数据库中存储项目状态。

有关 Terraform Cloud 功能的更多信息,请访问 官方文件

本教程是《如何使用Terraform管理基础设施》系列的一部分,该系列涵盖了许多Terraform主题,从首次安装Terraform到管理复杂项目。

Published At
Categories with 技术
comments powered by Disqus