如何在 DigitalOcean 中使用 Terraform

介绍

Terraform是构建和管理基础设施的一种有组织的方式的工具,您可以使用它来管理DigitalOcean Droplets、Load Balancers 甚至 DNS 条目,以及其他提供商提供的各种服务。

Terraform 通过阅读描述构成应用程序环境或数据中心的组件的配置文件来工作. 基于配置,它会生成一个执行计划,描述它将如何达到所需状态。

在本教程中,您将安装Terraform,并使用它在DigitalOcean上创建一个基础设施,该基础设施由两个NGINX服务器组成,其负载由DigitalOcean负载平衡器(https://www.digitalocean.com/products/load-balancer/)平衡。然后,您将使用Terraform在DigitalOcean上添加一个DNS条目,指向您的负载平衡器。

<$>[注] 注: 本教程已通过Terraform 1.1.3进行测试。

前提条件

要完成本教程,您将需要:

如果你没有一个, 注册一个新的帐户

  • 一个DigitalOcean个人访问代币,你可以通过DigitalOcean控制面板创建。 要做到这一点的说明可以在以下位置找到: 如何创建一个个人访问代币
  • 一个没有密码的SSH密钥添加到你的DigitalOcean帐户,你可以通过以下方式创建(https://andsky.com/tech/tutorials/how-to-use-ssh-keys-with-digitalocean-droplets) 。 当你添加密钥到你的帐户时,请记住你给它的名称,因为你需要它在本教程中。 (对于Terraform接受你的密钥的名称,它必须从一个字母或标签开始,并且只能包含字母,数字,标签和标签) MBR1 A

步骤 1 - 安装 Terraform

Terraform 是一个命令行工具,您可以在桌面或远程服务器上运行. 要安装它,您将下载并将其放置在您的PATH,以便您可以在您正在工作的任何目录中执行。

首先,从 官方下载页面下载适用于您的操作系统和架构的适当包。

在 macOS 上,使用此命令下载 Terraform 并将其放入您的主目录:

1curl -o ~/terraform.zip https://releases.hashicorp.com/terraform/1.1.3/terraform_1.1.3_darwin_amd64.zip

在 Linux 上,使用以下命令:

1curl -o ~/terraform.zip https://releases.hashicorp.com/terraform/1.1.3/terraform_1.1.3_linux_amd64.zip

创建~/opt/terraform目录:

1mkdir -p ~/opt/terraform

然后,使用unzip命令将 Terraform 解密到~/opt/terraform。在 Ubuntu 上,您可以使用apt安装unzip:

1sudo apt install unzip

使用它将下载的档案提取到 ~/opt/terraform 目录,运行:

1unzip ~/terraform.zip -d ~/opt/terraform

最后,将~/opt/terraform添加到您的PATH环境变量,以便您可以执行terraform命令,而无需指定可执行的完整路径。

在 Linux 上,您需要在.bashrc 中重新定义PATH,它在打开新壳时运行。

1nano ~/.bashrc

<$>[注意] 注意:在 macOS 上,如果使用 Bash,则将路径添加到文件 .bash_profile,如果使用 ZSH,则添加到 .zshrc

要将 Terraform 的路径附加到您的 PATH,请在文件末尾添加下列行:

1[label .bashrc]
2export PATH=$PATH:~/opt/terraform

保存并关闭文件,当你完成。

现在,你所有的新的壳会能够找到terraform命令. 要将新的PATH加载到当前的会话中,如果你在 Linux 系统上使用 Bash,请运行以下命令:

1. ~/.bashrc

如果您在 macOS 上使用 Bash,请执行此命令:

1. .bash_profile

如果您正在使用 ZSH,请运行此命令:

1. .zshrc

要验证您是否正确安装了 Terraform,请在没有参数的情况下运行terraform命令:

1terraform

您将看到类似于以下的输出:

 1[secondary_label Output]
 2Usage: terraform [global options] <subcommand> [args]
 3
 4The available commands for execution are listed below.
 5The primary workflow commands are given first, followed by
 6less common or more advanced commands.
 7
 8Main commands:
 9  init Prepare your working directory for other commands
10  validate Check whether the configuration is valid
11  plan Show changes required by the current configuration
12  apply Create or update infrastructure
13  destroy Destroy previously-created infrastructure
14
15All other commands:
16  console Try Terraform expressions at an interactive command prompt
17  fmt Reformat your configuration in the standard style
18  force-unlock Release a stuck lock on the current workspace
19  get Install or upgrade remote Terraform modules
20  graph Generate a Graphviz graph of the steps in an operation
21  import Associate existing infrastructure with a Terraform resource
22  login Obtain and save credentials for a remote host
23  logout Remove locally-stored credentials for a remote host
24  output Show output values from your root module
25  providers Show the providers required for this configuration
26  refresh Update the state to match remote systems
27  show Show the current state or a saved plan
28  state Advanced state management
29  taint Mark a resource instance as not fully functional
30  test Experimental support for module integration testing
31  untaint Remove the 'tainted' state from a resource instance
32  version Show the current Terraform version
33  workspace Workspace management
34
35Global options (use these before the subcommand, if any):
36  -chdir=DIR Switch to a different working directory before executing the
37                given subcommand.
38  -help Show this help output, or the help for a specified subcommand.
39  -version An alias for the "version" subcommand.

这些是Terraform接受的命令. 输出为您提供了简短的描述,您将在本教程中了解更多。

现在Terraform已安装,让我们将其配置为与DigitalOcean的资源一起工作。

步骤 2 — 配置 DigitalOcean 的 Terraform

Terraform通过您可以安装的 providers 支持各种服务提供商,每个服务提供商都有自己的规格,这些规格通常会与其相应的服务提供商的 API 进行映射。

DigitalOcean提供商允许Terraform与DigitalOcean API进行交互,以构建基础设施。

  • digitalocean_droplet:Dropplets (服务器)
  • digitalocean_loadbalancer:负载平衡器
  • digitalocean_domain: DNS 域名条目
  • digitalocean_record: DNS 记录

Terraform 将使用您的 DigitalOcean Personal Access Token 与 DigitalOcean API 进行通信,并管理您的帐户中的资源. 不要与他人共享此密钥,并将其保留在脚本和版本控制之外。

1export DO_PAT="your_personal_access_token"

这将使其在随后的命令中更容易使用,并将其与您的代码分开。

<$>[注] :如果您经常使用 Terraform 和 DigitalOcean,请使用您在上一步中修改PATH环境变量的相同方法将此行添加到您的壳配置文件中。

创建一个存储基础设施配置的目录,运行以下命令:

1mkdir ~/loadbalance

导航到新创建的目录:

1cd ~/loadbalance

Terraform 配置是以 .tf 文件扩展结束的文本文件,它们是人体可读的,它们支持评论(Terraform 也支持 JSON 格式的配置文件,但它们不会在这里被覆盖)。

通过Terraform构建基础设施的第一步是定义您将使用的提供商。

要使用 DigitalOcean 提供商与 Terraform,你必须告诉 Terraform 并配置插件与适当的凭证变量. 创建一个名为 provider.tf 的文件,该文件将为提供商存储配置:

1nano provider.tf

将下列行添加到文件中,告诉Terraform您想要使用DigitalOcean提供商,并指示Terraform在哪里找到它:

1[label ~/loadbalance/provider.tf]
2terraform {
3  required_providers {
4    digitalocean = {
5      source = "digitalocean/digitalocean"
6      version = "~> 2.0"
7    }
8  }
9}

然后,在文件中定义以下变量,以便您可以在其它配置文件中引用它们:

  • do_token:您的 DigitalOcean Personal Access Token.
  • pvt_key:私钥位置,因此Terraform可以使用它来登录新的Droplets并安装 Nginx。

运行时,您将将这些变量的值传输到Terraform,而不是在这里硬编码这些值,从而使配置更便携式。

要定义这些变量,请将这些行添加到文件中:

1[label ~/loadbalance/provider.tf]
2...
3variable "do_token" {}
4variable "pvt_key" {}

然后,添加这些行来配置 DigitalOcean 提供商,并指定您的 DigitalOcean 帐户的凭据,将do_token分配给提供者的token参数:

1[label ~/loadbalance/provider.tf]
2...
3provider "digitalocean" {
4  token = var.do_token
5}

最后,你会想让Terraform自动将你的SSH密钥添加到你创建的任何新Droplets中。当你将你的SSH密钥添加到DigitalOcean时,你给了它一个名字。Terraform可以使用这个名字来获取公共密钥。添加这些行,用你在DigitalOcean帐户中提供的密钥的名称代替terraform:

1[label ~/loadbalance/provider.tf]
2...
3data "digitalocean_ssh_key" "terraform" {
4  name = "terraform"
5}

您的完成的 provider.tf 文件将看起来像这样:

 1[label ~/loadbalance/provider.tf]
 2terraform {
 3  required_providers {
 4    digitalocean = {
 5      source = "digitalocean/digitalocean"
 6      version = "~> 2.0"
 7    }
 8  }
 9}
10
11variable "do_token" {}
12variable "pvt_key" {}
13
14provider "digitalocean" {
15  token = var.do_token
16}
17
18data "digitalocean_ssh_key" "terraform" {
19  name = "terraform"
20}

完成后,保存并关闭文件。

<$>[注] :将TF_LOG环境变量设置为1将允许详细记录Terraform正在尝试做什么。

1export TF_LOG=1

美元

将 Terraform 启动为您的项目,运行:

1terraform init

这将读取您的配置,并为您的提供商安装插件. 您将看到在输出中登录的:

 1[secondary_label Output]
 2Initializing the backend...
 3
 4Initializing provider plugins...
 5- Finding digitalocean/digitalocean versions matching "~> 2.0"...
 6- Installing digitalocean/digitalocean v2.16.0...
 7- Installed digitalocean/digitalocean v2.16.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 has been successfully initialized!
19
20You may now begin working with Terraform. Try running "terraform plan" to see
21any changes that are required for your infrastructure. All Terraform commands
22should now work.
23
24If you ever set or change modules or backend configuration for Terraform,
25rerun this command to reinitialize your working directory. If you forget, other
26commands will detect it and remind you to do so if necessary.

如果您碰巧陷入困境,而 Terraform 不像您预期的那样工作,您可以通过删除 terraform.tfstate 文件并手动破坏所创建的资源(例如,通过控制面板)重新开始。

Terraform 现在已配置并可连接到您的 DigitalOcean 帐户. 在下一步,您将使用 Terraform 来定义一个 Droplet 将运行 Nginx 服务器。

步骤 3 – 定义第一个 Nginx 服务器

您可以使用Terraform创建DigitalOcean Droplet并在Droplet上安装软件,一旦旋转,在此步骤中,您将提供一个Ubuntu 20.04 Droplet,并使用Terraform安装 Nginx Web服务器。

创建一个名为www-1.tf的新Terraform配置文件,其中将包含Droplet的配置:

1nano www-1.tf

插入以下行来定义 Droplet 资源:

1[label ~/loadbalance/www-1.tf]
2resource "digitalocean_droplet" "www-1" {
3    image = "ubuntu-20-04-x64"
4    name = "www-1"
5    region = "nyc3"
6    size = "s-1vcpu-1gb"
7    ssh_keys = [
8      data.digitalocean_ssh_key.terraform.id
9    ]

在之前的配置中,第一个行定义了一个名为www-1digitalocean_droplet 资源,其余的行指定了 Droplet 的属性,包括它将居住的数据中心和识别您要配置的 Droplet 的尺寸的粘土。

ssh_keys部分指定了您要添加到 Droplet 的公共密钥列表,在这种情况下,您正在指定您在provider.tf中定义的密钥。

当您对 DigitalOcean API 运行 Terraform 时,它会收集有关 Droplet 的各种信息,例如其公共和私人 IP 地址。

如果您想知道 Droplet 资源需要哪些参数或可选,请参阅官方 Terraform 文档: DigitalOcean Droplet Specification

要设置一个连接,Terraform 可以通过 SSH 连接到服务器,请在文件末尾添加以下行:

1[label ~/loadbalance/www-1.tf]
2...
3connection {
4    host = self.ipv4_address
5    user = "root"
6    type = "ssh"
7    private_key = file(var.pvt_key)
8    timeout = "2m"
9  }

这些行描述了Terraform应该如何连接到服务器,因此Terraform可以通过SSH连接到安装 Nginx。 注意使用私钥变量 var.pvt_key - 当您运行Terraform时,您将其值传输。

现在你已经建立了连接,配置远程执行提供器,你将使用它来安装 Nginx。

 1[label ~/loadbalance/www-1.tf]
 2...
 3provisioner "remote-exec" {
 4    inline = [
 5      "export PATH=$PATH:/usr/bin",
 6      # install nginx
 7      "sudo apt update",
 8      "sudo apt install -y nginx"
 9    ]
10  }
11}

请注意,在线数组中的字符串是 root 用户将运行安装 Nginx 的命令。

完成的檔案看起來像這樣:

 1[label ~/loadbalance/www-1.tf]
 2resource "digitalocean_droplet" "www-1" {
 3  image = "ubuntu-20-04-x64"
 4  name = "www-1"
 5  region = "nyc3"
 6  size = "s-1vcpu-1gb"
 7  ssh_keys = [
 8    data.digitalocean_ssh_key.terraform.id
 9  ]
10
11  connection {
12    host = self.ipv4_address
13    user = "root"
14    type = "ssh"
15    private_key = file(var.pvt_key)
16    timeout = "2m"
17  }
18
19  provisioner "remote-exec" {
20    inline = [
21      "export PATH=$PATH:/usr/bin",
22      # install nginx
23      "sudo apt update",
24      "sudo apt install -y nginx"
25    ]
26  }
27}

保存文件并离开编辑器. 你已经定义了服务器,并准备部署它,现在你会做。

步骤 4 — 使用 Terraform 创建 Nginx 服务器

您目前的 Terraform 配置描述了一个 Nginx 服务器,您现在将按照定义部署 Droplet。

运行terraform plan命令以查看 execution plan,或 Terraform 将尝试做什么来构建您所描述的基础设施. 您将需要指定您的 DigitalOcean Access Token 的值和您的私钥的路径,因为您的配置使用此信息来访问您的 Droplet 来安装 Nginx. 运行下面的命令来创建计划:

1terraform plan \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

<$>[警告] 警告:terraform plan命令支持-out参数来保存该计划.但是,该计划将存储API密钥,而Terraform不会加密这些数据。

你会看到类似于此的输出:

 1[secondary_label Output]
 2Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
 3  + create
 4
 5Terraform will perform the following actions:
 6
 7  # digitalocean_droplet.www-1 will be created
 8  + resource "digitalocean_droplet" "www-1" {
 9      + backups              = false
10      + created_at           = (known after apply)
11      + disk                 = (known after apply)
12      + graceful_shutdown    = false
13      + id                   = (known after apply)
14      + image                = "ubuntu-20-04-x64"
15      + ipv4_address         = (known after apply)
16      + ipv4_address_private = (known after apply)
17      + ipv6                 = false
18      + ipv6_address         = (known after apply)
19      + locked               = (known after apply)
20      + memory               = (known after apply)
21      + monitoring           = false
22      + name                 = "www-1"
23      + price_hourly         = (known after apply)
24      + price_monthly        = (known after apply)
25      + private_networking   = (known after apply)
26      + region               = "nyc3"
27      + resize_disk          = true
28      + size                 = "s-1vcpu-1gb"
29      + ssh_keys             = [
30          + "...",
31        ]
32      + status               = (known after apply)
33      + urn                  = (known after apply)
34      + vcpus                = (known after apply)
35      + volume_ids           = (known after apply)
36      + vpc_uuid             = (known after apply)
37    }
38
39Plan: 1 to add, 0 to change, 0 to destroy.
40
41───────────────────────────────────────────────────────────────
42
43Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.

+ 资源 digitalocean_droplet www-1`` 行意味着 Terraform 将创建一个名为 www-1` 的新的 Droplet 资源,随之随之而来的细节。

1terraform apply \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

您将获得与以前相同的输出,但这次,Terraform会问您是否想要继续:

1[secondary_label Output]
2...
3Plan: 1 to add, 0 to change, 0 to destroy.
4
5Do you want to perform these actions?
6  Terraform will perform the actions described above.
7  Only 'yes' will be accepted to approve.
8
9  Enter a value: yes

输入并点击ENTER。Terraform将提供您的Droplet:

1[secondary_label Output]
2digitalocean_droplet.www-1: Creating...

过了一会儿,你会看到Terraform用远程执行提供器安装 Nginx,然后这个过程就完成了:

 1[secondary_label Output]
 2
 3digitalocean_droplet.www-1: Provisioning with 'remote-exec'...
 4
 5....
 6
 7digitalocean_droplet.www-1: Creation complete after 1m54s [id=your_www-1_droplet_id]
 8
 9Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
10...

Terraform 创建了一个名为www-1的新 Droplet,并在其上安装了 Nginx. 如果您访问了新 Droplet 的公共 IP 地址,您将看到 Nginx 欢迎屏幕。在创建 Droplet 时显示了公共 IP,但您可以通过查看 Terraform 的当前状态来查看它。

若要查看环境的当前状态,请使用以下命令:

1terraform show terraform.tfstate

这将向您显示您的 Droplet 的公共 IP 地址。

 1[secondary_label Output]
 2resource "digitalocean_droplet" "www-1" {
 3    backups              = false
 4    created_at           = "..."
 5    disk                 = 25
 6    id                   = "your_www-1_droplet_id"
 7    image                = "ubuntu-20-04-x64"
 8    ipv4_address         = "your_www-1_server_ip"
 9    ipv4_address_private = "10.128.0.2"
10    ...

在您的浏览器中导航到http://your_www-1_server_ip,以验证您的 Nginx 服务器正在运行。

<$>[注] :如果您在Terraform之外修改基础设施,您的状态文件将过时。如果您的资源在Terraform以外被修改,则需要更新状态文件以使其更新。

1terraform refresh \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

美元

在此步骤中,您已经部署了您在Terraform中描述的Droplet,现在您将创建第二个。

步骤5:创建第二个 Nginx 服务器

现在您已经描述了 Nginx 服务器,您可以通过复制现有服务器的配置文件并更换 Droplet 资源的名称和主机名来快速添加一秒。

您可以手动做到这一点,但使用sed命令更快地读取www-1.tf文件,用www-2代替www-1的所有实例,并创建一个名为www-2.tf的新文件。

1sed 's/www-1/www-2/g' www-1.tf > www-2.tf

你可以通过访问使用 sed(https://www.digitalocean.com/community/tutorial_series/using-sed)来了解更多关于 sed 的信息。

再次运行terraform 计划,预览 Terraform 将进行的更改:

1terraform plan \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

输出显示,Terraform将创建第二个服务器,‘www-2’:

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

再次运行 Terraform Apply 来创建第二个 Droplet:

1terraform apply \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

就像以前一样,Terraform会要求您确认您想要继续,重新审查计划,然后键入以继续。

过了一会儿,Terraform会创建新的服务器并显示结果:

1[secondary_label Output]
2digitalocean_droplet.www-2: Creation complete after 1m47s [id=your_www-2_droplet_id]
3...
4Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Terraform 创建了新的服务器,而不改变现有的服务器,您可以重复此步骤以添加额外的 Nginx 服务器。

现在你有两个 Droplets 运行 Nginx,你将定义和部署负载平衡器来分割它们之间的流量。

步骤6:创建负荷平衡器

您将使用官方Terraform提供商支持的 DigitalOcean Load Balancer,以在两个Web服务器之间路由流量。

创建一个名为loadbalancer.tf的新 Terraform 配置文件:

1nano loadbalancer.tf

添加以下行来定义负载平衡器:

 1[label ~/loadbalance/loadbalancer.tf]
 2resource "digitalocean_loadbalancer" "www-lb" {
 3  name = "www-lb"
 4  region = "nyc3"
 5
 6  forwarding_rule {
 7    entry_port = 80
 8    entry_protocol = "http"
 9
10    target_port = 80
11    target_protocol = "http"
12  }
13
14  healthcheck {
15    port = 22
16    protocol = "tcp"
17  }
18
19  droplet_ids = [digitalocean_droplet.www-1.id, digitalocean_droplet.www-2.id ]
20}

负载平衡器定义指定其名称,它将位于的数据中心,它应该倾听的端口来平衡流量,健康检查的配置,以及它应该平衡的Dropplets的ID,您使用Terraform变量获取。

再次运行terraform plan命令,查看新的执行计划:

1terraform plan \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

您将看到几个输出行,包括以下行:

 1[secondary_label Output]
 2...
 3Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
 4  + create
 5
 6Terraform will perform the following actions:
 7
 8  # digitalocean_loadbalancer.www-lb will be created
 9  + resource "digitalocean_loadbalancer" "www-lb" {
10      + algorithm                        = "round_robin"
11      + disable_lets_encrypt_dns_records = false
12      + droplet_ids                      = [
13          + ...,
14          + ...,
15        ]
16      + enable_backend_keepalive         = false
17      + enable_proxy_protocol            = false
18      + id                               = (known after apply)
19      + ip                               = (known after apply)
20      + name                             = "www-lb"
21      + redirect_http_to_https           = false
22      + region                           = "nyc3"
23      + size_unit                        = (known after apply)
24      + status                           = (known after apply)
25      + urn                              = (known after apply)
26      + vpc_uuid                         = (known after apply)
27
28      + forwarding_rule {
29          + certificate_id   = (known after apply)
30          + certificate_name = (known after apply)
31          + entry_port       = 80
32          + entry_protocol   = "http"
33          + target_port      = 80
34          + target_protocol  = "http"
35          + tls_passthrough  = false
36        }
37
38      + healthcheck {
39          + check_interval_seconds   = 10
40          + healthy_threshold        = 5
41          + port                     = 22
42          + protocol                 = "tcp"
43          + response_timeout_seconds = 5
44          + unhealthy_threshold      = 3
45        }
46
47      + sticky_sessions {
48          + cookie_name        = (known after apply)
49          + cookie_ttl_seconds = (known after apply)
50          + type               = (known after apply)
51        }
52    }
53
54Plan: 1 to add, 0 to change, 0 to destroy.
55...

这意味着www-1www-2滴滴已经存在,Terraform将创建www-lb负载平衡器。

运行terraform应用来构建负载平衡器:

1terraform apply \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

再一次,Terraform会要求您审查该计划,通过输入来批准该计划。

一旦完成,您将看到输出,其中包含以下行,缩短为简短:

1[secondary_label Output]
2...
3digitalocean_loadbalancer.www-lb: Creating...
4...
5digitalocean_loadbalancer.www-lb: Creation complete after 1m18s [id=your_load_balancer_id]
6...
7Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
8...

使用terraform 显示 terraform.tfstate来查找您的负载平衡器的 IP 地址:

1terraform show terraform.tfstate

您将在www-lb条目下找到IP:

 1[secondary_label Output]
 2...
 3# digitalocean_loadbalancer.www-lb:
 4resource "digitalocean_loadbalancer" "www-lb" {
 5    algorithm                = "round_robin"
 6    disable_lets_encrypt_dns_records = false
 7    droplet_ids              = [
 8        your_www-1_droplet_id,
 9        your_www-2_droplet_id,
10    ]
11    enable_backend_keepalive = false
12    enable_proxy_protocol    = false
13    id                       = "your_load_balancer_id"
14    ip                       = "your_load_balancer_ip"
15    name                     = "www-lb"
16    ...

在浏览器中导航到http://your_load_balancer_ip,你会看到一个 Nginx 欢迎屏幕,因为负载平衡器正在向两个 Nginx 服务器之一发送流量。

现在您将学习如何使用Terraform为您的DigitalOcean帐户配置DNS。

步骤 7 – 创建 DNS 域名和记录

除了 Droplets 和 Load Balancers 之外,Terraform 还可以创建 DNS 域和记录域,例如,如果您想将您的域指向 Load Balancer,您可以写出描述该关系的配置。

<$>[注] 注: 使用自己的,独特的域名或Terraform将无法部署DNS资源。

创建一个新的文件来描述您的 DNS:

1nano domain_root.tf

添加以下域资源,以您的域名取代 your_domain:

1[label ~/loadbalance/domain_root.tf]
2resource "digitalocean_domain" "default" {
3   name = "your_domain"
4   ip_address = digitalocean_loadbalancer.www-lb.ip
5}

保存并关闭文件,当你完成。

您还可以添加一个 CNAME 记录,指向 www.your_domainyour_domain. 创建一个新的 CNAME 记录文件:

1nano domain_cname.tf

将这些行添加到文件中:

1[label domain_cname.tf]
2resource "digitalocean_record" "CNAME-www" {
3  domain = digitalocean_domain.default.name
4  type = "CNAME"
5  name = "www"
6  value = "@"
7}

保存并关闭文件,当你完成。

要添加 DNS 条目,运行terraform 计划,然后运行terraform 应用,就像其他资源一样。

导航到您的域名,您将看到一个 Nginx 欢迎屏幕,因为该域指向负载平衡器,该域将流量发送到两个 Nginx 服务器之一。

第8步:摧毁你的基础设施

虽然在生产环境中不常使用,但Terraform也可以破坏它所创造的基础设施,这在开发环境中主要有用,这些环境被部署和破坏了多次。

首先,创建一个执行计划以使用terraform plan -destroy来摧毁基础设施:

1terraform plan -destroy -out=terraform.tfplan \
2  -var "do_token=${DO_PAT}" \
3  -var "pvt_key=$HOME/.ssh/id_rsa"

Terraform 将输出具有红色标记的资源计划,并预先标记为减数标志,表示它将删除基础设施中的资源。

然后,使用terraform应用来运行该计划:

1terraform apply terraform.tfplan

Terraform将继续摧毁资源,如在生成的计划中所示。

结论

在本教程中,您使用Terraform在DigitalOcean上构建负载均衡的Web基础设施,在DigitalOcean负载均衡器背后运行两个Nginx Web服务器.您知道如何创建和破坏资源,查看当前状态,并使用Terraform配置DNS条目。

现在你已经了解了Terraform是如何工作的,你可以创建描述自己的项目的服务器基础设施的配置文件。本教程中的示例是一个很好的起点,它展示了如何自动部署服务器。

Terraform 拥有更多功能,可以与其他供应商合作,请参阅官方 Terraform 文档以了解您如何使用 Terraform 来改善自己的基础设施。

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

Published At
Categories with 技术
comments powered by Disqus