如何在DigitalOcean中使用Terraform

郜俊晤
2023-12-01

介绍 (Introduction)

Terraform is a tool for building and managing infrastructure in an organized way. It can be used to manage DigitalOcean droplets and DNS entries, in addition to a large variety of services offered by other providers. It is controlled via an easy to use command-line interface, and can run from your desktop or a remote server.

Terraform是一种用于以有组织的方式构建和管理基础结构的工具。 除了其他提供商提供的各种服务之外,它还可以用于管理DigitalOcean Drops和DNS条目。 它通过易于使用的命令行界面进行控制,并且可以从台式机或远程服务器上运行。

Terraform works by reading configuration files that describe the components that make up your application environment or datacenter. Based on the configuration, it generates an execution plan, which describes what it will do to reach the desired state. The plan is then executed to build the infrastructure. When changes to the configuration occur, Terraform can generate and execute incremental plans to update the existing infrastructure to the newly described state.

Terraform通过读取描述构成您的应用程序环境或数据中心的组件的配置文件来工作。 根据配置,它会生成一个执行计划,该计划描述了为达到所需状态将要执行的操作。 然后执行该计划以构建基础结构。 当配置发生更改时,Terraform可以生成并执行增量计划,以将现有基础结构更新为新描述的状态。

In this tutorial, you’ll use Terraform to create an infrastructure that consists of two Nginx servers that are load balanced by a DigitalOcean load balancer. Then you’ll use Terraform to add a DNS entry on DigitalOcean that points to your load balancer. This will help you get started with using Terraform, and give you an idea of how you can use it to manage and deploy a DigitalOcean-based infrastructure that meets your own needs.

在本教程中,您将使用Terraform创建由两个由DigitalOcean负载均衡器进行负载均衡的Nginx服务器组成的基础架构。 然后,您将使用Terraform在DigitalOcean上添加一个指向您的负载均衡器的DNS条目。 这将帮助您开始使用Terraform,并让您了解如何使用它来管理和部署满足您自己需求的基于DigitalOcean的基础结构。

This tutorial uses Terraform 0.12.

本教程使用Terraform 0.12。

先决条件 (Prerequisites)

To complete this tutorial, you’ll need:

要完成本教程,您需要:

第1步-配置环境 (Step 1 — Configuring your Environment)

Terraform will use your DigitalOcean Personal Access Token to communicate with the DigitalOcean API and manage resources in your account. Don’t share this key with others, and keep it out of scripts and version control. Export your DigitalOcean Personal Access Token to an environment variable called DO_PAT. This will make using it in subsequent commands easier and keep it separate from your code:

Terraform将使用您的DigitalOcean个人访问令牌与DigitalOcean API通信并管理您帐户中的资源。 不要与他人共享此密钥,并且不要将其保存在脚本和版本控制中。 将您的DigitalOcean个人访问令牌导出到名为DO_PAT的环境变量。 这将使在后续命令中更容易使用它,并使它与代码分开:

  • export DO_PAT={YOUR_PERSONAL_ACCESS_TOKEN}

    导出DO_PAT = {YOUR_PERSONAL_ACCESS_TOKEN}

Next, you’ll need the MD5 fingerprint of the public key you’ve associated with your account, so Terraform can add it to each machine it provisions. Assuming that your private key is located at ~/.ssh/id_rsa, use the following command to get the MD5 fingerprint of your public key:

接下来,您将需要与您的帐户关联的公钥的MD5指纹,以便Terraform可以将其添加到所配置的每台机器上。 假设您的私钥位于~/.ssh/id_rsa ,请使用以下命令获取您的公钥的MD5指纹:

  • ssh-keygen -E md5 -lf ~/.ssh/id_rsa.pub | awk '{print $2}'

    ssh-keygen -E md5 -lf〜/ .ssh / id_rsa.pub | awk'{print $ 2}'

This will output something like the following:

这将输出类似以下内容:


   
   
Output
md5:e7:42:16:d7:...9e:92:f7

You will provide this fingerprint, minus the md5: prefix, when running Terraform. To make this easier, export your SSH fingerprint to your environment as well:

运行Terraform时,将提供此指纹(减去md5:前缀)。 为了简化此操作,请将您的SSH指纹也导出到您的环境中:

  • export DO_SSH_FINGERPRINT="e7:42:16:d7:e5:a0:43:29:82:7d:a0:59:cf:9e:92:f7"

    导出DO_SSH_FINGERPRINT =“ e7:42:16:d7:e5:a0:43:29:82:7d:a0:59:cf:9e:92:f7 ”

Now that you have your environment variables configured, let’s install Terraform.

现在,您已经配置了环境变量,让我们安装Terraform。

第2步-安装Terraform (Step 2 — Installing Terraform)

Terraform can run on your desktop or on a remote server. To install it, download it and place it on your PATH.

Terraform可以在您的桌面或远程服务器上运行。 要安装它,请下载它并将其放在PATH

First, download the appropriate package for your OS and architecture from the official Downloads page. For this tutorial, download Terraform to your local machine and save it to the ~/Downloads directory.

首先,从官方下载页面下载适合您的操作系统和体系结构的软件包。 对于本教程,请将Terraform下载到本地计算机,然后将其保存到~/Downloads目录。

If you’re on macOS or Linux, you can download Terraform with curl.

如果您使用的是macOS或Linux,则可以下载带有curl Terraform。

On macOS, use this command to download Terraform and place it in the Downloads folder:

在macOS上,使用以下命令下载Terraform并将其放置在Downloads文件夹中:

  • curl -o https://releases.hashicorp.com/terraform/0.12.24/terraform_0.12.24_darwin_amd64.zip ~/Downloads/terraform.zip

    curl -o https://releases.hashicorp.com/terraform/ 0.12.24 / terraform_ 0.12.24 _darwin_amd64.zip〜/ Downloads / terraform.zip

On Linux, use this command:

在Linux上,使用以下命令:

  • curl -O https://releases.hashicorp.com/terraform/0.12.24/terraform_0.12.24_linux_amd64.zip ~/Downloads/terraform.zip

    curl -O https://releases.hashicorp.com/terraform/ 0.12.24 / terraform_ 0.12.24_linux _amd64.zip〜/ Downloads / terraform.zip

Then extract Terraform and place it in the ~/opt/terraform directory with the following commands:

然后使用以下命令解压缩Terraform并将其放置在~/opt/terraform目录中:

  • mkdir -p ~/opt/terraform

    mkdir -p〜 / opt / terraform

  • unzip ~/Downloads/terraform.zip -d ~/opt/terraform

    解压缩〜/ Downloads / terraform.zip -d〜 / opt / terraform

This unarchives the package to the opt/terraform/ directory, within your home directory.

这会将程序包取消存档到主目录中的opt/terraform/目录。

Finally, add ~/opt/terraform/bin, to your PATH environment variable so you can execute the terraform command without specifying the full path to the executable.

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

On Linux, add the path to the file .bashrc:

在Linux上,将路径添加到文件.bashrc

  • nano ~/.bashrc

    纳米〜/ .bashrc

To append Terraform’s path to your PATH, add the following line at the end of the file:

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

.bashrc
.bashrc
export PATH=$PATH:~/opt/terraform/bin

Save the file and exit the editor

保存文件并退出编辑器

Now all of your new bash sessions will be able to find the terraform command. To load the new PATH into your current session, type the following:

现在,您所有的新bash会话都将能够找到terraform命令。 要将新的PATH加载到当前会话中,请键入以下内容:

  • . .bashrc

    。 .bashrc

If you’re on macOS and you’re using the Bash shell, add the code to .bash_profile instead. On macOS with zsh, add the line to ~/.zshrc.

如果您使用的是macOS,并且使用的是Bash shell,请改为将代码添加到.bash_profile 。 在具有zsh macOS上,将该行添加到~/.zshrc

To verify that you have installed Terraform correctly, let’s try and run it. In a terminal, run Terraform:

要验证您是否正确安装了Terraform,让我们尝试运行它。 在终端中,运行Terraform:

  • terraform

    地貌

If your path is set up properly, you will see output that is similar to the following:

如果您的路径设置正确,您将看到类似于以下内容的输出:


   
   
Output
Available commands are: apply Builds or changes infrastructure graph Create a visual graph of Terraform resources output Read an output from a state file plan Generate and show an execution plan refresh Update local state file against real resources show Inspect Terraform state or plan version Prints the Terraform version

These are the commands that Terraform accepts. Their brief described here, but we will get into how to use them later.

这些是Terraform接受的命令。 这里简要介绍了它们,但是稍后我们将介绍如何使用它们。

Now that Terraform is installed, let’s start writing a configuration to describe our infrastructure!

现在已经安装了Terraform,让我们开始编写配置来描述我们的基础架构!

第3步-为DigitalOcean配置Terraform (Step 3 — Configuring Terraform for DigitalOcean)

Terraform supports a variety of service providers through providers that ship with it. We are interested in DigitalOcean provider, which Terraform will use to interact with the DigitalOcean API to build our infrastructure. The first step to building an infrastructure with Terraform is to define the provider you’re going to use by creating some Terraform configuration files.

Terraform通过其附带的提供程序来支持各种服务提供程序 。 我们对DigitalOcean提供商感兴趣,Terraform将使用该提供商与DigitalOcean API进行交互以构建我们的基础架构。 使用Terraform构建基础结构的第一步是通过创建一些Terraform配置文件来定义要使用的提供程序。

Create a directory that will store your configuration files for a given project. The name of the directory does not matter, but we will use “loadbalance” for the example (feel free to change its name):

创建一个目录,该目录将存储给定项目的配置文件。 目录的名称无关紧要,但是我们将使用“ loadbalance”作为示例(可以随意更改其名称):

  • mkdir ~/loadbalance

    mkdir〜 /负载平衡

Terraform configurations are text files that end with the .tf file extension. They are human-readable and they support comments. Terraform also supports JSON-format configuration files, but we won’t cover those here. Terraform will read all of the configuration files in your working directory in a declarative manner, so the order of resource and variable definitions do not matter. Your entire infrastructure can exist in a single configuration file, but we will separate our configuration files by resources in this tutorial.

Terraform配置是以.tf文件扩展名结尾的文本文件。 它们是人类可读的,并且支持注释。 Terraform还支持JSON格式的配置文件,但此处不再赘述。 Terraform将以声明方式读取工作目录中的所有配置文件,因此资源顺序和变量定义无关紧要。 您的整个基础结构可以存在于单个配置文件中,但是在本教程中,我们将按资源将配置文件分开。

Change your current directory to the newly created directory:

将当前目录更改为新创建的目录:

  • cd ~/loadbalance

    cd〜 /负载平衡

From now on, we will assume that your working directory is the one that we just changed to. If you start a new terminal session, be sure to change to the directory that contains your Terraform configuration.

从现在开始,我们将假定您的工作目录是我们刚刚更改的目录。 如果开始新的终端会话,请确保更改为包含Terraform配置的目录。

If you happen to get stuck, and Terraform is not working as you expect, you can start over by deleting the terraform.tfstate file, and manually destroying the resources that were created (e.g. through the control panel.

如果碰巧被卡住了,并且Terraform无法按预期工作,则可以通过删除terraform.tfstate文件并手动销毁已创建的资源(例如通过控制面板)来重新开始。

Note: You may also want to enable logging to stdout, so you can see what Terraform is trying to do. Do that by running the following command:

注意 :您可能还希望启用到stdout的日志记录,因此可以查看Terraform试图执行的操作。 通过运行以下命令来做到这一点:

  • export TF_LOG=1

    导出TF_LOG = 1

The first step to using the DigitalOcean provider is configuring it with the proper credential variables. Let’s do that now.

使用DigitalOcean提供程序的第一步是为其配置适当的凭据变量。 现在开始吧。

Create a file called provider.tf:

创建一个名为provider.tf的文件:

  • nano provider.tf

    纳米提供商

Add the following lines into the file:

将以下行添加到文件中:

provider.tf
provider.tf
variable "do_token" {}
variable "pub_key" {}
variable "pvt_key" {}
variable "ssh_fingerprint" {}

provider "digitalocean" {
  token = var.do_token
}

Save and exit. Here is a breakdown of the first four lines:

保存并退出。 这是前四行的细分:

  • variable “do_token”: your DigitalOcean Personal Access Token

    变量“ do_token” :您的DigitalOcean个人访问令牌

  • variable “pub_key”: public key location, so it can be installed into new droplets

    变量“ pub_key” :公钥位置,因此可以将其安装到新的Droplet中

  • variable “pvt_key”: private key location, so Terraform can connect to new droplets

    变量“ pvt_key” :私钥位置,因此Terraform可以连接到新的Droplet

  • variable “ssh_fingerprint”: fingerprint of SSH key

    变量“ ssh_fingerprint” :SSH密钥的指纹

The other lines specify the credentials for your DigitalOcean account by assigning “token” to the do_token variable. We will pass the values of these variables into Terraform, when we run it.

其他行通过为do_token变量分配“令牌”来指定DigitalOcean帐户的凭据。 运行它时,我们会将这些变量的值传递给Terraform。

The official Terraform documentation for the DigitalOcean provider is located here: DigitalOcean Provider.

DigitalOcean提供商的官方Terraform文档位于: DigitalOcean Provider

Each provider has its own specifications, which generally map to the API of its respective service provider. In the case of the DigitalOcean provider, we are able to define three types of resources:

每个提供商都有自己的规范,这些规范通常映射到其各自服务提供商的API。 对于DigitalOcean提供程序,我们能够定义三种类型的资源:

  • digitalocean_droplet: Droplets (servers)

    digitalocean_droplet :Droplet(服务器)

  • digitalocean_loadbalancer: Load balancer

    digitalocean_loadbalancer :负载均衡器

  • digitalocean_domain: DNS domain entries

    digitalocean_domain :DNS域条目

  • digitalocean_record: DNS records

    digitalocean_record :DNS记录

Let’s start by creating a Droplet which will run an Nginx server.

让我们从创建一个运行Nginx服务器的Droplet开始。

步骤4 —定义第一个Nginx服务器 (Step 4 — Defining the First Nginx Server)

You can use Terraform to create a DigitalOcean Droplet and install software on the Droplet once it spins up. In this step you’ll provision a single Ubuntu 18.04 Droplet and install the Nginx web server using Terraform.

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

Create a new Terraform configuration file called www-1.tf which will hold the configuration for the Droplet:

创建一个名为www-1.tf的新Terraform配置文件,该文件将保存Droplet的配置:

  • nano www-1.tf

    纳米www-1.tf

Insert the following lines to define the Droplet resource:

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

resource "digitalocean_droplet" "www-1" {
    image = "ubuntu-18-04-x64"
    name = "www-1"
    region = "nyc2"
    size = "s-1vcpu-1gb"
    private_networking = true
    ssh_keys = [
      var.ssh_fingerprint
    ]

In the preceding configuration, the first line defines a digitalocean_droplet resource named www-1. The rest of the lines specify the droplet’s attributes, including its data center and the slug which identifies the size of the Droplet you want to configure. In this case we’re using s-1vcpu-1gb, which will create a Droplet with one CPU and 1GB of RAM. Visit this size slug chart to see the available slugs you can use.

在前面的配置中,第一行定义了一个名为www-1digitalocean_droplet资源。 其余各行指定了液滴的属性,包括其数据中心和用于确定要配置的液滴大小的块。 在这种情况下,我们使用s-1vcpu-1gb ,它将创建一个具有一个CPU和1GB RAM的Droplet。 请访问此大小段塞图表,以查看可以使用的可用段

When you run Terraform against the DigitalOcean API, it will collect a variety of information about the Droplet, such as its public and private IP addresses. This information can be used by other resources in your configuration.

当您对DigitalOcean API运行Terraform时,它将收集有关Droplet的各种信息,例如其公共IP地址和私有IP地址。 此信息可由配置中的其他资源使用。

If you are wondering which arguments are required or optional for a Droplet resource, please refer to the official Terraform documentation: DigitalOcean Droplet Specification.

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

Now, we will set up a connection which Terraform can use to connect to the server via SSH. Insert the following lines at the end of the file:

现在,我们将建立一个connection ,Terraform可使用该连接通过SSH连接到服务器。 在文件末尾插入以下行:

connection {
    host = self.ipv4_address
    user = "root"
    type = "ssh"
    private_key = file(var.pvt_key)
    timeout = "2m"
  }

These lines describe how Terraform should connect to the server, so Terraform can connect over SSH to install Nginx: (note the use of the private key variable).

这些行描述了Terraform如何连接到服务器,因此Terraform可以通过SSH连接以安装Nginx :(请注意使用私钥变量)。

Now that you have the connection set up, configure the remote-exec provisioner, which you’ll use to install Nginx. Add the following lines to the configuration to do just that:

既然已经建立了连接,请配置用于安装Nginx的remote-exec Provisioner。 在配置中添加以下几行即可:

provisioner "remote-exec" {
    inline = [
      "export PATH=$PATH:/usr/bin",
      # install nginx
      "sudo apt-get update",
      "sudo apt-get -y install nginx"
    ]
  }
}

Note that the strings in the inline array are the commands that the root user will run to install Nginx.

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

The completed file looks like this:

完成的文件如下所示:

www-1.tf
www-1.tf
resource "digitalocean_droplet" "www-1" {
    image = "ubuntu-18-04-x64"
    name = "www-1"
    region = "nyc2"
    size = "s-1vcpu-1gb"
    private_networking = true
    ssh_keys = [
      var.ssh_fingerprint
    ]
  connection {

    host = self.ipv4_address
    user = "root"
    type = "ssh"
    private_key = file(var.pvt_key)
    timeout = "2m"
  }
  provisioner "remote-exec" {
    inline = [
      "export PATH=$PATH:/usr/bin",
      # install nginx
      "sudo apt-get update",
      "sudo apt-get -y install nginx"
    ]
  }
}

Save the file and exit the editor.

保存文件并退出编辑器。

第5步—使用Terraform创建Nginx服务器 (Step 5 — Using Terraform to Create the Nginx Server)

Currently, your Terraform configuration describes a single Nginx server. Let’s test it out.

当前,您的Terraform配置描述了一个Nginx服务器。 让我们测试一下。

First, initialize Terraform for your project. This will read your configuration files and install the plugins for your provider:

首先,为您的项目初始化Terraform。 这将读取您的配置文件并为您的提供商安装插件:

  • terraform init

    地形初始化

You’ll see this output:

您将看到以下输出:


   
   
Output
1 resource "digitalocean_droplet" "www-1" { Initializing the backend... Initializing provider plugins... - Checking for available provider plugins... - Downloading plugin for provider "digitalocean" (terraform-providers/digitalocean) 1.6.0... The following providers do not have any version constraints in configuration, so the latest version was installed. To prevent automatic upgrades to new major versions that may contain breaking changes, it is recommended to add version = "..." constraints to the corresponding provider blocks in configuration, with the constraint strings suggested below. * provider.digitalocean: version = "~> 1.18" 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.

Next, run the terraform plan command to see what Terraform will attempt to do to build the infrastructure you described (i.e. see the execution plan). You will have to specify the values for your DigitalOcean Access Token, the path to your public and private key, and the fingerprint for your key, as your Terraform configuration files use this information to access the DigitalOcean API and log in to your Droplet to install Nginx. Execute the following command:

接下来,运行terraform plan命令以查看Terraform将尝试做什么来构建您描述的基础结构(即,查看执行计划)。 您必须指定DigitalOcean访问令牌的值,公钥和私钥的路径以及密钥的指纹,因为Terraform配置文件使用此信息来访问DigitalOcean API并登录到Droplet进行安装Nginx。 执行以下命令:

  • terraform plan \

    地形计划
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=${DO_SSH_FINGERPRINT}"

    -var“ ssh_fingerprint = $ {DO_SSH_FINGERPRINT} ”

You’ll see this output:

您将看到以下输出:


   
   
Output
Refreshing Terraform state in-memory prior to plan... The refreshed state will be used to calculate this plan, but will not be persisted to local or remote state storage. ------------------------------------------------------------------------ An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # digitalocean_droplet.www-1 will be created + resource "digitalocean_droplet" "www-1" { + backups = false + created_at = (known after apply) + disk = (known after apply) + id = (known after apply) + image = "ubuntu-18-04-x64" + ipv4_address = (known after apply) + ipv4_address_private = (known after apply) + ipv6 = false + ipv6_address = (known after apply) + ipv6_address_private = (known after apply) + locked = (known after apply) + memory = (known after apply) + monitoring = false + name = "www-1" + price_hourly = (known after apply) + price_monthly = (known after apply) + private_networking = true + region = "nyc2" + resize_disk = true + size = "s-1vcpu-1gb" + ssh_keys = [ + "your_ssh_key_hash, ] + status = (known after apply) + urn = (known after apply) + vcpus = (known after apply) + volume_ids = (known after apply) + vpc_uuid = (known after apply) } Plan: 1 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------

The + digitalocean_droplet.www-1 line means that Terraform will create a new droplet resource called www-1, with the details that follow it. That’s exactly what we want, so let’s execute the plan. Run the following terraform apply command to execute the current plan. Again, specify all the values for the variables:

+ digitalocean_droplet.www-1行意味着Terraform将创建一个名为www-1的新液滴资源,并附带其后的详细信息。 这正是我们想要的,所以让我们执行计划。 运行以下terraform apply命令以执行当前计划。 再次,指定变量的所有值:

  • terraform apply \

    地形适用
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=${DO_SSH_FINGERPRINT}"

    -var“ ssh_fingerprint = $ {DO_SSH_FINGERPRINT} ”

You’ll see the same output as before, but this time, Terraform will ask you if you want to proceed:

您将看到与以前相同的输出,但是这次,Terraform将询问您是否要继续:


   
   
Output
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

Enter yes and press ENTER. Terraform will provision your Droplet:

输入yes ,然后按ENTER 。 Terraform将配置您的Droplet:


   
   
Outut
digitalocean_droplet.www-1: Creating...

After a bit of time, you’ll see Terraform installing Nginx with the remote-exec provisioner, and then the process will complete:

一段时间后,您将看到Terraform使用remote-exec提供者安装Nginx,然后该过程将完成:

digitalocean_droplet.www-1: Provisioning with 'remote-exec'...

....


digitalocean_droplet.www-1: Creation complete

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

Terraform updates the state file terraform.tfstate every time it executes a plan or “refreshes” its state.

每当执行计划或“刷新”其状态时,Terraform都会更新状态文件terraform.tfstate

To view the current state of your environment, use the following command:

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

  • terraform show terraform.tfstate

    terraform显示terraform.tfstate

Note: If you modify your infrastructure outside of Terraform, your state file will be out of date. If your resources are modified outside of Terraform, you may refresh the state file to bring it up to date. This command will pull the updated resource information from your provider(s):

注意 :如果在Terraform之外修改基础架构,则状态文件将过时。 如果在Terraform之外修改了资源,则可以刷新状态文件以使其更新。 此命令将从您的提供程序中获取更新的资源信息:

  • terraform refresh \

    地形刷新
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=$DO_SSH_FINGERPRINT"

    -var“ ssh_fingerprint = $ DO_SSH_FINGERPRINT ”

At this point, Terraform has created a new Droplet called www-1 and installed Nginx on it. If you visit the public IP address of your new Droplet, you’ll see the Nginx welcome screen.

此时,Terraform已经创建了一个名为www-1的新Droplet,并在其上安装了Nginx。 如果您访问新Droplet的公共IP地址,则会看到Nginx欢迎屏幕。

步骤6 —创建第二个Nginx服务器 (Step 6 — Creating the Second Nginx Server)

Now that you have described an Nginx server, you can add a second quickly by copying the existing server’s configuration file and replacing the name and hostname of the Droplet resource.

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

You can do this manually, but it’s faster to use the sed command to substitute all instances of www-1 with www-2 and create a new file. Here is the sed command to do that:

您可以手动执行此操作,但是使用sed命令将www-1所有实例替换为www-2并创建一个新文件会更快。 这是sed命令执行的操作:

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

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

Learn more about sed in Using sed.

使用sed中了解有关sed更多信息。

Now run terraform plan again to preview the changes that Terraform will make:

现在再次运行terraform plan以预览Terraform将进行的更改:

  • terraform plan \

    地形计划
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=${DO_SSH_FINGERPRINT}"

    -var“ ssh_fingerprint = $ {DO_SSH_FINGERPRINT} ”

The output shows the second server:

输出显示第二台服务器:


   
   
Output
... Terraform will perform the following actions: # digitalocean_droplet.www-2 will be created + resource "digitalocean_droplet" "www-2" { + backups = false + disk = (known after apply) + id = (known after apply) + image = "ubuntu-18-04-x64" + ipv4_address = (known after apply) + ipv4_address_private = (known after apply) + ipv6 = false + ipv6_address = (known after apply) + ipv6_address_private = (known after apply) + locked = (known after apply) + memory = (known after apply) + monitoring = false + name = "www-2" + price_hourly = (known after apply) + price_monthly = (known after apply) + private_networking = true + region = "nyc2" + resize_disk = true + size = "s-1vcpu-1gb" + ssh_keys = [ + "your_ssh_key_hash, ] + status = (known after apply) + urn = (known after apply) + vcpus = (known after apply) + volume_ids = (known after apply) } Plan: 1 to add, 0 to change, 0 to destroy. ...

Then run terraform apply again to create the second server.

然后再次运行terraform apply创建第二个服务器。

  • terraform apply \

    地形适用
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=${DO_SSH_FINGERPRINT}"

    -var“ ssh_fingerprint = $ {DO_SSH_FINGERPRINT} ”

You have both servers configured. Now let’s configure the load balancer.

您已经配置了两个服务器。 现在,让我们配置负载均衡器。

第7步-创建负载均衡器 (Step 7 — Creating the Load balancer)

We’ll use a DigitalOcean Load Balancer to route traffic between our two web servers. The DigitalOcean Terraform provider supports this as well.

我们将使用DigitalOcean负载平衡器在两个Web服务器之间路由流量。 DigitalOcean Terraform提供程序也支持此功能。

Create a new Terraform configuration file called loadbalancer.tf:

创建一个新的Terraform配置文件,称为loadbalancer.tf

  • nano loadbalancer.tf

    纳米负载平衡器

Insert the following lines to define the load balancer:

插入以下行以定义负载均衡器:

loadbalancer.tf
负载均衡器
resource "digitalocean_loadbalancer" "www-lb" {
  name = "web-lb"
  region = "nyc2"

  forwarding_rule {
    entry_port = 80
    entry_protocol = "http"

    target_port = 80
    target_protocol = "http"
  }

  healthcheck {
    port = 22
    protocol = "tcp"
  }

  droplet_ids = [digitalocean_droplet.www-1.id, digitalocean_droplet.www-2.id ]
}

The load balancer definition specifies the name of the load balancer, the datacenter, the ports it should listen on to balance traffic, configuration for the health check, and the IDs of the Droplets it should balance, which we fetch using Terraform variables.

负载平衡器定义指定了负载平衡器的名称,数据中心,它应侦听以平衡流量的端口,运行状况检查的配置以及应平衡的Droplet的ID(我们使用Terraform变量获取)。

Save the file and exit the editor.

保存文件并退出编辑器。

Run terraform plan command again to see the new execution plan:

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

  • terraform plan \

    地形计划
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=$DO_SSH_FINGERPRINT"

    -var“ ssh_fingerprint = $ DO_SSH_FINGERPRINT ”

You’ll see several lines of output, including the following lines:

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


   
   
Output
... digitalocean_droplet.www-1: Refreshing state... [id=155205581] digitalocean_droplet.www-2: Refreshing state... [id=155305680] ... + digitalocean_loadbalancer.www-lb ...

This means that the www-1 and www-2 Droplets already exist, and Terraform will create the haproxy-www Droplet. Let’s run terraform apply to build the remaining components:

这意味着www-1www-2 Droplet已经存在,并且Terraform将创建haproxy-www Droplet。 让我们运行terraform apply来构建其余组件:

  • terraform apply \

    地形适用
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=$DO_SSH_FINGERPRINT"

    -var“ ssh_fingerprint = $ DO_SSH_FINGERPRINT ”

You’ll see output that contains the following lines (truncated for brevity):

您将看到包含以下行的输出(为简洁起见,将其截断):


   
   
Output
... digitalocean_loadbalancer.web-lb: Creating... ... digitalocean_loadbalancer.web-lb: Creation complete after 1m18s [id=e517d65b-68a3-4923-82c3-28bc48e50c12] ... Apply complete! Resources: 1 added, 0 changed, 0 destroyed. ...

If you visit the public IP address of the www-lb Droplet, you’ll see an Nginx welcome screen, because the load balancer is sending traffic to one of the two Nginx servers.

如果访问www-lb Droplet的公共IP地址,则会看到一个Nginx欢迎屏幕,因为负载平衡器正在将流量发送到两个Nginx服务器之一。

The rest of the tutorial includes information about configuring DNS domain and record resources with Terraform, and information on how to use the other Terraform commands.

本教程的其余部分包括有关使用Terraform配置DNS域和记录资源的信息,以及有关如何使用其他Terraform命令的信息。

步骤8 —创建DNS域和记录 (Step 8 — Creating DNS Domains and Records)

Terraform can also create DNS domain and record domains. For example, if you want to point your domain to your load balancer, you can create a Terraform configuration file for that.

Terraform还可以创建DNS域并记录域。 例如,如果要将域指向负载均衡器,则可以为此创建Terraform配置文件。

Note: Use your own, unique, domain name or this step will fail.

注意:使用您自己的唯一域名,否则此步骤将失败。

Create a new file to describe your DNS:

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

  • nano your_domain.tf

    纳米your_domain.tf

Insert the following domain resource:

插入以下域资源:

your_domain.tf
your_domain.tf
resource "digitalocean_domain" "default" {
   name = "your_domain"
   ip_address = digitalocean_loadbalancer.www-lb.ipv4_address
}

And while we’re at it, let’s add a CNAME record that points www.your_domain to your_domain:

在进行此操作时,让我们添加一个CNAME记录,该记录将www .your_domain指向your_domain

your_domain.tf
your_domain.tf
resource "digitalocean_record" "CNAME-www" {
  domain = digitalocean_domain.default.name
  type = "CNAME"
  name = "www"
  value = "@"
}

Save and exit.

保存并退出。

To add the DNS entries, run terraform plan followed by terraform apply, as with the other resources.

要添加DNS条目,请与其他资源一样运行terraform plan然后运行terraform apply

第9步-销毁您的基础架构 (Step 9 — Destroying Your Infrastructure)

Although not commonly used in production environments, Terraform can also destroy infrastructures that it creates. This is mainly useful in development environments that are built and destroyed multiple times.

尽管在生产环境中不常用,但Terraform也会破坏其创建的基础结构。 这主要在多次构建和销毁的开发环境中很有用。

First, create an execution plan to destroy the infrastructure by using terraform plan -destroy like this:

首先,使用terraform plan -destroy创建执行计划以破坏基础架构,如下所示:

  • terraform plan -destroy -out=terraform.tfplan \

    terraform计划-destroy -out = terraform.tfplan \
  • -var "do_token=${DO_PAT}" \

    -var“ do_token = $ {DO_PAT}” \
  • -var "pub_key=$HOME/.ssh/id_rsa.pub" \

    -var“ pub_key = $ HOME /.ssh/id_rsa.pub” \

  • -var "pvt_key=$HOME/.ssh/id_rsa" \

    -var“ pvt_key = $ HOME /.ssh/id_rsa” \

  • -var "ssh_fingerprint=$DO_SSH_FINGERPRINT"

    -var“ ssh_fingerprint = $ DO_SSH_FINGERPRINT ”

Terraform will output a plan with resources marked in red, and prefixed with a minus sign, indicating that it will delete the resources in your infrastructure.

Terraform将输出一个计划,该计划的资源标记为红色,并带有一个负号前缀,表明它将删除基础架构中的资源。

Use terraform apply to run the plan:

使用terraform apply运行计划:

  • terraform apply terraform.tfplan

    terraform应用terraform.tfplan

Terraform will destroy the resources, as indicated in the destroy plan.

如销毁计划中所示,Terraform将销毁资源。

结论 (Conclusion)

In this tutorial you used Terraform to build a load-balanced web infrastructure on DigitalOcean, with two Nginx web servers running behind a DigitalOcean Load Balancer. You know how to create and destroy resources, and use Terraform to configure DNS entries.

在本教程中,您使用Terraform在DigitalOcean上构建了负载平衡的Web基础结构,其中两个Nginx Web服务器在DigitalOcean Load Balancer后面运行。 您知道如何创建和销毁资源,以及如何使用Terraform配置DNS条目。

Now that you understand how Terraform works, feel free to create configuration files that describe a server infrastructure that is useful to you. The example setup is simple, but demonstrates how easy it is to automate the deployment of servers. If you already use configuration management tools, like Puppet or Chef, you can call those with Terraform’s provisioners to configure servers as part of their creation process.

既然您了解了Terraform的工作原理,就可以随意创建描述对您有用的服务器基础结构的配置文件。 示例设置很简单,但是演示了自动化服务器部署非常容易。 如果您已经使用了Puppet或Chef之类的配置管理工具,则可以通过Terraform的供应商调用这些服务器来配置服务器,这是服务器创建过程的一部分。

Terraform has many more features, and can work with other providers. Check out the official Terraform Documentation to learn more about how you can use Terraform to improve your own infrastructure.

Terraform具有更多功能,并且可以与其他提供程序一起使用。 查看官方Terraform文档以了解有关如何使用Terraform改进自己的基础结构的更多信息。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-terraform-with-digitalocean

 类似资料: