Terraform
构建基础设施
安装 Terraform 后,您就可以首次创建基础设施了。
在本教程中,您将使用 Terraform 在 Oracle Cloud Infrastructure (OCI) 上部署虚拟云网络 (VCN)。其他 OCI 资源需要部署到 VCN 中。
先决条件
要遵循本教程,您需要
- OCI 租户。请注意您的区域,您将在整个教程中用到它。
- 已安装 Terraform CLI。
- 已安装 OCI CLI。
从您的终端配置 OCI CLI。
$ oci session authenticate
Enter a region by index or name(e.g.
1: ap-chiyoda-1, 2: ap-chuncheon-1, 3: ap-hyderabad-1, 4: ap-melbourne-1, 5: ap-mumbai-1,
6: ap-osaka-1, 7: ap-seoul-1, 8: ap-sydney-1, 9: ap-tokyo-1, 10: ca-montreal-1,
11: ca-toronto-1, 12: eu-amsterdam-1, 13: eu-frankfurt-1, 14: eu-zurich-1, 15: me-dubai-1,
16: me-jeddah-1, 17: sa-santiago-1, 18: sa-saopaulo-1, 19: uk-cardiff-1, 20: uk-gov-cardiff-1,
21: uk-gov-london-1, 22: uk-london-1, 23: us-ashburn-1, 24: us-gov-ashburn-1, 25: us-gov-chicago-1,
26: us-gov-phoenix-1, 27: us-langley-1, 28: us-luke-1, 29: us-phoenix-1, 30: us-sanjose-1):
按照提示输入您拥有 OCI 租户的区域。浏览器窗口会自动打开,并提示您输入 OCI 用户名和密码。输入它们并单击“登录”按钮。然后返回到您的终端。它会显示一条成功消息,这意味着您已使用默认配置集配置了 OCI CLI。
Completed browser authentication process!
Config written to: /Users/dos/.oci/config
Try out your newly created session credentials with the following example command:
oci iam region list --config-file /Users/dos/.oci/config --profile DEFAULT --auth security_token
现在使用其他命名配置集配置 OCI CLI。
$ oci session authenticate
Enter a region by index or name(e.g.
1: ap-chiyoda-1, 2: ap-chuncheon-1, 3: ap-hyderabad-1, 4: ap-melbourne-1, 5: ap-mumbai-1,
6: ap-osaka-1, 7: ap-seoul-1, 8: ap-sydney-1, 9: ap-tokyo-1, 10: ca-montreal-1,
11: ca-toronto-1, 12: eu-amsterdam-1, 13: eu-frankfurt-1, 14: eu-zurich-1, 15: me-dubai-1,
16: me-jeddah-1, 17: sa-santiago-1, 18: sa-saopaulo-1, 19: uk-cardiff-1, 20: uk-gov-cardiff-1,
21: uk-gov-london-1, 22: uk-london-1, 23: us-ashburn-1, 24: us-gov-ashburn-1, 25: us-gov-chicago-1,
26: us-gov-phoenix-1, 27: us-langley-1, 28: us-luke-1, 29: us-phoenix-1, 30: us-sanjose-1):
按照提示输入您拥有 OCI 租户的区域。浏览器窗口会自动打开,并提示您输入 OCI 用户名和密码。输入它们并单击“登录”按钮。然后返回到您的终端。它会显示一条成功消息,并提示您输入配置集名称。
Completed browser authentication process!
Enter the name of the profile you would like to create:
输入 learn-terraform 作为您的配置集名称。
Enter the name of the profile you would like to create: learn-terraform
Config written to: /Users/<your-home-directory>/.oci/config
Try out your newly created session credentials with the following example command:
oci iam region list --config-file /Users/<your-home-directory>/.oci/config --profile learn-terraform --auth security_token
输出将打印 CLI 存储令牌的位置。Terraform 稍后将在本教程中自动检测到该令牌,并使用那里的凭据来创建基础设施。该令牌具有 1 小时的时间限制 (TTL)。如果它过期,请通过提供配置集名称来刷新它。
$ oci session refresh --profile learn-terraform
Attempting to refresh token from https://auth.us-sanjose-1.oraclecloud.com/v1/authentication/refresh
Successfully refreshed token
编写配置
用于描述 Terraform 中基础设施的一组文件称为 Terraform 配置。您将编写您的第一个配置来定义一个 OCI VCN。
每个 Terraform 配置都必须位于自己的工作目录中。为您的配置创建一个目录。
创建 learn-terraform-oci 目录。
$ mkdir learn-terraform-oci
更改到 learn-terraform-oci 目录。
$ cd learn-terraform-oci
创建一个文件来定义您的基础设施。
$ touch main.tf
在您的文本编辑器中打开 main.tf 并粘贴以下配置。
terraform {
required_providers {
oci = {
source = "oracle/oci"
}
}
}
provider "oci" {
region = "us-sanjose-1"
auth = "SecurityToken"
config_file_profile = "learn-terraform"
}
resource "oci_core_vcn" "internal" {
dns_label = "internal"
cidr_block = "172.16.0.0/20"
compartment_id = "<your_compartment_OCID_here>"
display_name = "My internal VCN"
}
自定义以下值
region- 值应与您的 OCI 区域匹配。compartment_id- 值应与您的“OCID”匹配,您可以通过单击 OCI 控制台右上角的个人资料图标并从下拉菜单中选择“租户:您的用户名”来获取它。
保存自定义的文件。
这是一个您可以与 Terraform 部署的完整配置。在接下来的部分中,我们将更详细地回顾此配置的每个块。
Terraform 块
Terraform {} 块包含 Terraform 设置,包括 Terraform 将用于配置你的基础设施的必需的提供器。对于每个提供器,source 属性定义了一个可选的主机名、命名空间和提供器类型。Terraform 默认从 Terraform Registry 安装提供器。在这个示例配置中,oci 提供器的源被定义为 oracle/oci,这是 registry.terraform.io/oracle/oci 的简写。
你还可以为在 required_providers 块中定义的每个提供器设置版本约束。 version 属性是可选的,但我们建议使用它来约束提供器版本,以防止 Terraform 安装与你的配置不兼容的提供器版本。如果你没有指定提供器版本,Terraform 将在初始化期间自动下载最新版本。
要了解更多信息,请参考 提供器源文档。
提供器
provider 块配置指定的提供器,在本例中为 oci。提供器是一个插件,Terraform 使用它来创建和管理你的资源。
OCI 提供器块中的 config_file_profile 属性引用 Terraform 用于存储 OCI CLI 在你配置它时创建的文件中的令牌凭据。切勿在你的配置文件中硬编码凭据或其他机密信息。与其他类型的代码一样,你可以使用源代码管理共享和管理你的 Terraform 配置文件,因此硬编码机密值可能会将它们暴露给攻击者。
你可以在 Terraform 配置中使用多个提供器块来管理来自不同提供器的资源。你甚至可以将不同的提供器一起使用。例如,你可以将 OCI 实例的 IP 地址传递给来自 DataDog 的监控资源。
资源
使用 resource 块来定义你的基础设施组件。资源可以是物理或虚拟组件,例如 VCN,也可以是逻辑资源,例如 Heroku 应用程序。
资源块在块之前有两个字符串:资源类型和资源名称。在本例中,资源类型是 oci_core_vcn,名称是 internal。类型的前缀映射到提供器的名称,在本例中为 oci。资源类型和资源名称共同构成了 Terraform 的资源唯一 ID。例如,你的 VCN 的 ID 是 oci_core_vcn.internal。
资源块包含参数,你使用这些参数来配置资源。示例配置包含设置 DNS 标签、VCN 的 CIDR 块、你的 OCID 和显示名称的参数。 OCI 提供器文档 记录了 OCI 提供器中每个资源的必需和可选参数。
初始化目录
当你创建一个新的配置时,或者从版本控制中检出现有的配置时,你需要使用 terraform init 初始化目录。
初始化配置目录会下载并安装配置中定义的提供器,在本例中为 oci 提供器。
初始化目录。
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of oracle/oci...
- Installing oracle/oci v5.7.0...
- Installed oracle/oci v5.7.0 (signed by a HashiCorp partner, key ID 1533A49284137CEB)
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 会下载 oci 提供器并将其安装到你当前工作目录的隐藏子目录中,名为 .terraform。 terraform init 命令会打印出安装了哪个版本的提供器。Terraform 还会创建一个名为 .terraform.lock.hcl 的锁文件,该文件指定了使用的确切提供器版本,以便你可以控制何时更新项目使用的提供器。
格式化并验证配置
我们建议在所有配置文件中使用一致的格式。 terraform fmt 命令会自动更新当前目录中的配置,以提高可读性和一致性。
格式化您的配置。Terraform 会打印出它修改过的文件的名称(如果有)。在本例中,您的配置文件已经正确格式化,因此 Terraform 不会返回任何文件名。
$ terraform fmt
您还可以使用 terraform validate 命令确保您的配置在语法上有效且内部一致。
验证您的配置。上述提供的示例配置是有效的,因此 Terraform 将返回一条成功消息。
$ terraform validate
Success! The configuration is valid.
创建基础设施
现在使用 terraform apply 命令应用配置。Terraform 将打印类似于以下内容的输出。为了节省空间,我们截断了一些输出。
$ terraform apply
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:
# oci_core_vcn.internal will be created
+ resource "oci_core_vcn" "internal" {
+ byoipv6cidr_blocks = (known after apply)
+ cidr_block = "172.16.0.0/20"
+ cidr_blocks = (known after apply)
+ compartment_id = "ocid1.tenancy.oc1...."
+ default_dhcp_options_id = (known after apply)
+ default_route_table_id = (known after apply)
+ default_security_list_id = (known after apply)
+ defined_tags = (known after apply)
+ display_name = "My internal VCN"
+ dns_label = "internal"
+ freeform_tags = (known after apply)
+ id = (known after apply)
+ ipv6cidr_blocks = (known after apply)
+ ipv6private_cidr_blocks = (known after apply)
+ is_ipv6enabled = (known after apply)
+ is_oracle_gua_allocation_enabled = (known after apply)
+ state = (known after apply)
+ time_created = (known after apply)
+ vcn_domain_name = (known after apply)
}
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:
在应用任何更改之前,Terraform 会打印出 *执行计划*,其中描述了 Terraform 将采取的操作,以便将您的基础设施更改为与配置匹配。
输出格式类似于 Git 等工具生成的 diff 格式。输出具有 + 符号,紧随其后的是 oci_core_vcn.internal,这意味着 Terraform 将创建此资源。在下方,它显示了将设置的属性。当显示的值为 (known after apply) 时,这意味着在创建资源之前无法知道该值。例如,OCI 在创建 VCN 时分配自己的 ID,因此 Terraform 无法知道 ID 属性的值,直到您应用更改并且 OCI 提供程序从 OCI API 返回该值。
Terraform 现在将暂停并等待您的批准才能继续。如果计划中的任何内容看起来不正确或危险,则可以在此处安全地中止,而不会对您的基础设施进行任何更改。
在这种情况下,该计划是可以接受的,因此在确认提示符处键入 yes 以继续。执行计划需要几分钟,因为 Terraform 会等待 VCN 变为可用状态。
Enter a value: yes
oci_core_vcn.internal: Creating...
oci_core_vcn.internal: Creation complete after 1s [id=ocid1.vcn.oc1.us-sanjose-1.amaaaaaapqqlmeyaklull6tpfms534aoijpjwpkzjo25rxqiqhadgdzodnua]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
您现在已经使用 Terraform 创建了基础设施!访问 OCI 控制台 VCN 页面,选择您的区隔,并找到您新建的 VCN,列为“My internal VCN”。
检查状态
当你应用你的配置时,Terraform 会将数据写入名为 terraform.tfstate 的文件中。Terraform 将其管理资源的 ID 和属性存储在此文件中,以便以后可以更新或销毁这些资源。
Terraform 状态文件是 Terraform 跟踪其管理的资源的方式,通常包含敏感信息,因此您必须安全地存储状态文件,并且仅将其分发给需要管理您的基础设施的可信团队成员。在生产环境中,我们建议使用 HCP Terraform 或 Terraform Enterprise 远程存储您的状态。Terraform 还支持其他几个 远程后端,您可以使用它们来存储和管理您的状态。
使用 terraform show 检查当前状态。
$ terraform show
# oci_core_vcn.internal:
resource "oci_core_vcn" "internal" {
cidr_block = "172.16.0.0/20"
cidr_blocks = [
"172.16.0.0/20",
]
compartment_id = "ocid1.tenancy.oc1...."
default_dhcp_options_id = "ocid1.dhcpoptions.oc1.us-sanjose-1.aaaaaaaa6odqyurw4mf7jmf3jy6ehtw6n32ohyogy4w5c43qoubgewyxr2va"
default_route_table_id = "ocid1.routetable.oc1.us-sanjose-1.aaaaaaaan3n6iazjfubarvwwtszl3v6gdzqvfoccdj555p2ujehbo4tlu7ma"
default_security_list_id = "ocid1.securitylist.oc1.us-sanjose-1.aaaaaaaant6vlu2y77pwwzjubmzg6czzvo2laii4h3p5d7w2nqcr4fey5gaa"
defined_tags = {
"Oracle-Tags.CreatedBy" = "oracleidentitycloudservice/redacted"
"Oracle-Tags.CreatedOn" = "2021-04-07T18:25:06.555Z"
}
display_name = "My internal VCN"
dns_label = "internal"
freeform_tags = {}
id = "ocid1.vcn.oc1.us-sanjose-1.amaaaaaapqqlmeyaklull6tpfms534aoijpjwpkzjo25rxqiqhadgdzodnua"
ipv6cidr_blocks = []
ipv6private_cidr_blocks = []
is_ipv6enabled = false
state = "AVAILABLE"
time_created = "2021-04-07 18:25:06.558 +0000 UTC"
vcn_domain_name = "internal.oraclevcn.com"
}
当 Terraform 创建此 VCN 时,它还从 OCI 提供程序收集了大量关于它的信息。这些值可以被引用以配置其他资源或输出,我们稍后会在这些教程中进一步讨论。
手动管理状态
Terraform 有一个名为 terraform state 的内置命令,用于高级状态管理。例如,您可能需要列出项目中状态中的资源,您可以使用 list 子命令来获取。
$ terraform state list
oci_core_vcn.internal
下一步
现在你已经使用 Terraform 创建了你的第一个基础设施,请继续到下一个教程来修改你的基础设施。
有关我们在此教程中使用的概念的更多详细信息
- Terraform OCI Provider 文档
- 官方 OCI Terraform 文档
- Terraform Registry – OCI 模块(可重用的 Terraform 配置)