Terraform
检测基础设施漂移并强制执行策略
随着组织的壮大和基础设施预置工作流的成熟,仅靠培训和手动构建工具来强制执行一致性和最佳实践变得越来越困难。Terraform 可以通过资源和模块特定的条件,自动检查您的基础设施是否满足行业最佳实践和组织特定的标准。前置条件和后置条件可帮助您在 Terraform 配置中定义资源要求。通过在模块定义中包含自定义条件,您可以确保下游使用者遵守配置标准,并正确使用模块。此外,您可以使用 HCP Terraform 通过工作空间特定的运行任务来验证您的基础设施,并使用 HashiCorp Sentinel 或 Open Policy Agent (OPA) 来实施工作空间或组织范围的策略。
在本教程中,您将使用 Terraform 前置条件和策略来验证配置并强制遵守组织惯例。首先,您将使用 Terraform 前置条件来强制执行网络安全约定。然后,您将学习如何在 HCP Terraform 中配置和实施策略,以防止在特定日期进行基础设施部署。最后,您将使用 HCP Terraform 的漂移检测来检测基础设施设置何时与您编写的 Terraform 配置不一致。
前置条件和后置条件可帮助您在 Terraform 配置中定义资源要求。通过在模块定义中包含自定义条件,您可以确保下游使用者遵守配置标准,并正确使用模块。
先决条件
本教程假设您熟悉 Terraform 和 HCP Terraform 工作流。如果您是 Terraform 新手,请先完成入门教程。如果您是 HCP Terraform 新手,请先完成HCP Terraform 入门教程。
为了完成本教程,您需要以下条件
- Terraform v1.4+ 本地安装。
- 一个AWS 账户。
- 一个拥有已 本地通过身份验证 的 HCP Terraform 账户,并支持 HCP Terraform。
- 一个已使用您的 AWS 凭证 配置的 HCP Terraform 变量集。
创建示例存储库
访问本教程的模板存储库。点击Use this template按钮并选择Create a New Repository。选择您用于 HCP Terraform 的 GitHub 所有者,并将新存储库命名为learn-terraform-drift-and-policy。将其余设置保留为默认值。
克隆示例配置
克隆您的示例存储库,将USER替换为您自己的 GitHub 用户名。您将在本教程后面将更改推送到此分支。
$ git clone https://github.com/USER/learn-terraform-drift-and-policy
切换到仓库目录。
$ cd learn-terraform-drift-and-policy
查看基础设施配置
此存储库包含一个定义网络和堡垒主机的本地 Terraform 模块,以及使用该模块的根配置。它还包含 Sentinel 策略和 OPA 策略定义,您将在本教程后面进行查看。
├── LICENSE
├── README.md
├── main.tf
├── modules
│ └── network
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── opa
│ ├── policies
│ │ ├── friday_deploys.rego
│ │ └── public_ingress.rego
│ └── policies.hcl
├── sentinel
│ ├── policies
│ │ ├── deployment_days.sentinel
│ │ ├── mocks
│ │ │ ├── aws_security_groups_allowed.sentinel
│ │ │ └── aws_security_groups_forbidden.sentinel
│ │ ├── public_ingress.sentinel
│ │ └── test
│ │ ├── deployment_days
│ │ │ ├── allowed_day.hcl
│ │ │ └── forbidden_day.hcl
│ │ └── public_ingress
│ │ ├── allowed_sgs.hcl
│ │ └── forbidden_sgs.hcl
│ └── sentinel.hcl
├── terraform.auto.tfvars
├── terraform.tf
└── variables.tf
在代码编辑器中打开modules/network/main.tf文件。此配置使用公共vpc模块来预置网络资源,包括公共和私有子网以及 NAT 网关。然后,它在其中一个公共子网中启动一个堡垒主机。
modules/network/main.tf
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.13.0"
cidr = var.vpc_cidr
azs = data.aws_availability_zones.available.names
private_subnets = var.private_subnet_cidrs
public_subnets = var.public_subnet_cidrs
enable_nat_gateway = true
enable_vpn_gateway = false
enable_dns_hostnames = true
}
resource "aws_security_group" "bastion" {
name = "bastion_ssh"
vpc_id = module.vpc.vpc_id
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["192.80.0.0/16"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
data "aws_ec2_instance_type" "bastion" {
instance_type = var.bastion_instance_type
}
resource "aws_instance" "bastion" {
instance_type = var.bastion_instance_type
ami = data.aws_ami.amazon_linux.id
subnet_id = module.vpc.public_subnets[0]
vpc_security_group_ids = [aws_security_group.bastion.id]
}
堡垒主机旨在作为 VPC 私有子网中实例的 SSH 流量的单一入口点。配置还包括一个安全组,将任何入站 SSH 流量限制到堡垒主机的 192.80.0.0/16 CIDR 块,这是代表您的组织网络的示例 CIDR。
尽管此配置在本地引用此模块,但在较大的组织中,您可能会将其发布到 Terraform Registry 中。通过在网络配置的样板中包含堡垒主机,您可以为网络中的实例建立 SSH 访问标准。
定义前置条件
network模块定义了一个bastion_instance_type输入变量,允许用户根据预期的使用情况和工作负载进行调整。过度预置堡垒主机将给您的组织带来不必要的成本。因此,虽然您希望允许用户指定实例类型,但您不希望允许他们预置过大的实例。您将添加一个前置条件来验证实例类型的核心数不超过 2 个,以保持较低的运营成本。
首先,将以下数据源添加到模块配置中。它从 AWS Provider 访问实例类型详细信息,包括核心数。
modules/network/main.tf
data "aws_ec2_instance_type" "bastion" {
instance_type = var.bastion_instance_type
}
现在,将前置条件添加到aws_instance.bastion资源定义中。
modules/network/main.tf
resource "aws_instance" "bastion" {
instance_type = var.bastion_instance_type
ami = data.aws_ami.amazon_linux.id
subnet_id = module.vpc.public_subnets[0]
vpc_security_group_ids = [aws_security_group.bastion.id]
lifecycle {
precondition {
condition = data.aws_ec2_instance_type.bastion.default_cores <= 2
error_message = "Change the value of bastion_instance_type to a type that has 2 or fewer cores to avoid over provisioning."
}
}
}
Terraform 会在创建计划之前评估前置条件并检查配置是否满足条件。在这种情况下,Terraform 会在创建预置堡垒实例和其他资源的计划之前,检查aws_ec2_instance_type.bastion数据源中的default_cores值是否小于或等于 2 个核心。
部署基础设施
根 Terraform 配置使用network模块创建堡垒主机和网络组件,包括 VPC、子网、NAT 网关和路由表。
它在terraform.auto.tfvars文件中设置输入变量的值。堡垒实例类型的初始值为t2.2xlarge,它有 8 个核心,会如预期般导致前置条件失败。
terraform.auto.tfvars
bastion_instance_type = "t2.2xlarge"
aws_region = "us-east-2"
将您的 HCP Terraform 组织名称设置为环境变量,以配置您的 HCP Terraform 集成。
$ export TF_CLOUD_ORGANIZATION=
初始化配置。作为初始化的一部分,Terraform 会创建您的learn-terraform-drift-and-policy HCP Terraform 工作空间。
$ terraform init
现在,尝试规划您的配置。计划将失败,因为您指定的实例大小过大,并且前置条件将返回错误。
$ terraform plan
Running plan in HCP Terraform. Output will stream here. Pressing Ctrl-C
will stop streaming the logs, but will not stop the plan running remotely.
Preparing the remote plan...
To view this run in a browser, visit:
https://app.terraform.io/app/your-org/learn-terraform-drift-and-policy/runs/run-uADaudsn745HtpAv
Waiting for the plan to start...
Terraform v1.8.3
on linux_amd64
Initializing plugins and modules...
module.network.data.aws_ami.amazon_linux: Refreshing...
module.network.data.aws_ec2_instance_type.bastion: Refreshing...
module.network.data.aws_availability_zones.available: Refreshing...
module.network.data.aws_ec2_instance_type.bastion: Refresh complete after 0s [id=t2.2xlarge]
module.network.data.aws_availability_zones.available: Refresh complete after 0s [id=us-east-2]
module.network.data.aws_ami.amazon_linux: Refresh complete after 0s [id=ami-02c4341ce4964ef28]
╷
│ Error: Resource precondition failed
│
│ on modules/network/main.tf line 67, in resource "aws_instance" "bastion":
│ 67: condition = data.aws_ec2_instance_type.bastion.default_cores <= 2
│ ├────────────────
│ │ data.aws_ec2_instance_type.bastion.default_cores is 8
│
│ Change the value of bastion_instance_type to a type that has 2 or fewer
│ cores to avoid over provisioning.
╵
Operation failed: failed running terraform plan (exit 1)
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Note: 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.
t2.2xlarge实例类型有 8 个核心,因此此 Terraform 运行未能通过网络模块中定义的前置条件。
将terraform.auto.tfvars中的bastion_instance_type变量更改为t2.small。
terraform.auto.tfvars
bastion_instance_type = "t2.small"
aws_region = "us-east-2"
现在应用您的配置。前置条件将通过,Terraform 将规划您的更改。对提示回复yes以确认操作。
$ terraform apply
Running apply in HCP Terraform. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.
Preparing the remote apply...
To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-training/learn-terraform-drift-and-policy/runs/run-tCk6Da4HDNQdqQHT
Waiting for the plan to start...
Terraform v1.8.3
on linux_amd64
Initializing plugins and modules...
module.network.data.aws_ami.amazon_linux: Refreshing...
module.network.data.aws_availability_zones.available: Refreshing...
module.network.data.aws_ec2_instance_type.bastion: Refreshing...
module.network.data.aws_ec2_instance_type.bastion: Refresh complete after 0s [id=t2.small]
module.network.data.aws_availability_zones.available: Refresh complete after 0s [id=us-east-2]
module.network.data.aws_ami.amazon_linux: Refresh complete after 0s [id=ami-02c4341ce4964ef28]
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:
# module.network.aws_instance.bastion will be created
+ resource "aws_instance" "bastion" {
## ...
Plan: 25 to add, 0 to change, 0 to destroy.
Do you want to perform these actions in workspace "learn-terraform-drift-and-policy"?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
module.network.module.vpc.aws_vpc.this[0]: Creating...
module.network.module.vpc.aws_vpc.this[0]: Still creating... [10s elapsed]
module.network.module.vpc.aws_vpc.this[0]: Creation complete after 11s [id=vpc-0c8dcf0e5d6c4da5b]
## ...
module.network.module.vpc.aws_nat_gateway.this[1]: Creation complete after 1m34s [id=nat-0b1a2fb0d660bf641]
module.network.module.vpc.aws_route.private_nat_gateway[1]: Creating...
module.network.module.vpc.aws_route.private_nat_gateway[0]: Creating...
module.network.module.vpc.aws_route.private_nat_gateway[0]: Creation complete after 1s [id=r-rtb-018b4e4a1e29501a41080289494]
module.network.module.vpc.aws_route.private_nat_gateway[1]: Creation complete after 1s [id=r-rtb-0ab827442f9e9d12f1080289494]
Apply complete! Resources: 25 added, 0 changed, 0 destroyed.
使用前置条件验证资源分配使您能够使用来自 AWS 的最新信息来确定您的配置是否满足要求。虽然您也可以使用变量验证来捕获违规,但这需要研究所有实例类型及其容量,并在配置中列出所有可接受的实例类型,使其灵活性较差。
查看策略
配置级别的验证(例如变量约束和前置条件)允许您在编写配置时就推广标准。但是,模块作者和用户必须自愿遵守这些标准。模块作者必须在模块定义中包含条件,用户必须使用这些模块来预置基础设施。为了在整个工作空间或组织中强制执行基础设施标准,您可以使用 HCP Terraform 策略,它不需要您的用户以特定方式编写基础设施配置。
HCP Terraform 允许您选择 Sentinel 或 Open Policy Agent (OPA) 作为策略引擎。本教程包含两种策略引擎的策略。选择下面的选项卡,使用您偏好的策略引擎继续本教程。
导航到示例存储库中的sentinel目录。
$ cd sentinel
打开sentinel.hcl文件以查看策略集配置。
sentinel/sentinel.hcl
policy "friday_deploys" {
source = "./policies/deployment_days.sentinel"
enforcement_level = "advisory"
}
policy "public_ingress" {
source = "./policies/public_ingress.sentinel"
enforcement_level = "soft-mandatory"
}
此策略集定义了两个策略:friday_deploys 和 public_ingress。它将friday_deploys策略的执行级别设置为advisory,将public_ingress策略的执行级别设置为mandatory。当 HCP Terraform 检测到 advisory 策略失败时,它会通知您失败情况,但仍允许您预置资源。当 mandatory 策略失败时,HCP Terraform 将拒绝应用计划,直到策略通过为止。查询格式引用了策略文件中声明的包名称以及为策略定义的规则名称。
除了对基础设施配置设置护栏之外,您可能还希望强制执行组织工作流本身的标准。一个常见的做法是防止在周五进行基础设施部署,以降低周末前发生生产事故的风险。friday_deploys策略可防止在某一周的某天进行基础设施部署。
示例策略包括测试,以便您可以在将它们与 HCP Terraform 一起使用之前验证它们是否按预期工作。现在运行您的策略测试。
接下来,测试您的策略。
$ sentinel test policies/
PASS - deployment_days.sentinel
PASS - test/deployment_days/allowed_day.hcl
PASS - test/deployment_days/forbidden_day.hcl
PASS - public_ingress.sentinel
PASS - test/public_ingress/allowed_sgs.hcl
PASS - test/public_ingress/forbidden_sgs.hcl
2 tests completed in 10.661875ms
Sentinel 从与每个策略名称匹配的目录中加载测试。
public_ingress策略会解析 Terraform 运行的计划更改,并检查它们是否包含允许来自所有 CIDR (0.0.0.0/0) 的公共入站流量的安全组更新。此策略通过防止创建任何过于宽松的安全组来帮助强制执行您的安全态势。
public_ingress.sentinel
import "tfplan/v2" as tfplan
# List of forbidden ingress CIDRs
forbidden_ingress_cidrs = ["0.0.0.0/0"]
# Function to check if a CIDR is in the forbidden list
is_forbidden_cidr = func(cidr) {
return cidr in forbidden_ingress_cidrs
}
check_security_groups = func() {
violatingResources = filter tfplan.resource_changes as _, rc {
rc.type is "aws_security_group" and
rc.mode is "managed" and
(rc.change.actions contains "create" or rc.change.actions is ["update"]) and
rc.change.after.ingress is not null and
any rc.change.after.ingress as _, ingress {
ingress.cidr_blocks is not null and
any ingress.cidr_blocks as _, cidr {
is_forbidden_cidr(cidr)
}
}
}
return length(violatingResources) == 0
}
main = rule {
check_security_groups()
}
创建策略集
HCP Terraform 以策略集的形式组织策略。策略集可以包含 Sentinel 或 OPA 策略。您可以将策略集应用于整个组织,或仅应用于特定工作空间。
有三种方法可以管理策略集及其策略:VCS 存储库、HCP Terraform API 或直接通过 HCP Terraform UI。在本教程中,您将通过 VCS 配置策略集。VCS 工作流允许您协作并安全地开发和版本化 OPA 策略,将存储库建立为事实来源。
现在您将创建策略集。
首先,登录 HCP Terraform,然后选择您将用于完成本教程的组织。
导航到组织的 Settings,然后导航到 Policy Sets。点击 Connect a new policy set。
选择 Version control provider (VCS) 选项。
在 Configure settings 页面上
- 根据您在本教程中使用的策略引擎,选择 Sentinel 或 Open Policy Agent 作为策略集成。
- 将策略命名为
learn-terraform-drift-and-policy。 - 将 Scope of Policies 设置为 Policies enforced on selected workspaces
- 在 Workspaces 下,选择您的
learn-terraform-drift-and-policy工作空间。 - 在 Overrides 下,取消选中 "This policy set can be overridden in the event of mandatory failures." 旁边的复选框。
- 点击 Next(下一步)。
在 Connect to VCS 页面上
- 选择您的 Github.com 集成。
- 选择您为本教程创建的
learn-terraform-drift-and-policy存储库。 - 根据您在本教程中使用的策略引擎,将 Policies path 设置为
/sentinel或/opa。 - 点击 Next(下一步)。
在 Parameters 页面上
- 点击 + Add parameter 按钮。
- 将 Key 设置为
forbidden_days,并将值设置为包含今天的列表,例如:["Monday"]。 - 点击 Save parameter 按钮。
- 点击 Connect policy set 按钮将您的策略集连接到 HCP Terraform。
HCP Terraform 将打印出新策略集的摘要。
触发策略违规
您之前预置的网络资源包括一个堡垒主机,该主机配置了一个安全组,用于限制入站流量到组织的内部网络。想象一下,一位工程师正在对生产事故进行故障排除,并试图通过放宽安全组的限制来绕过此限制。
要模拟此情况,请在modules/network/main.tf中更新aws_security_group.bastion资源的入站规则。
resource "aws_security_group" "bastion" {
name = "bastion_ssh"
vpc_id = module.vpc.vpc_id
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
在存储库的根目录中运行terraform apply,尝试更新安全组。应用将如预期失败,因为入站规则过于宽松。
$ terraform apply
Running apply in HCP Terraform. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.
Preparing the remote apply...
To view this run in a browser, visit:
https://app.terraform.io/app/your-org/learn-terraform-drift-and-policy/runs/run-JC5aXmZipJBq28gp
Waiting for the plan to start...
Terraform v1.9.6
on linux_amd64
Initializing plugins and modules...
##...
Plan: 0 to add, 1 to change, 0 to destroy.
Post-plan Tasks:
------------------------------------------------------------------------
Policy Evaluations
Evaluating ... (4s elapsed)
--------------------------------
Sentinel Policy Evaluation
→→ Overall Result: FAILED
This result means that one or more Sentinel policies failed. More than likely, this was due to the discovery of violations by the main rule and other sub rules
2 policies evaluated
→ Policy set 1: learn-terraform-drift-and-policy (2)
↳ Policy name: friday_deploys.sentinel
| ✓ Passed
| No description available
↳ Policy name: public_ingress.sentinel
| × Failed
| No description available
╷
│ Error: Task Stage failed.
│
HCP Terraform 检测到策略失败:安全组允许公共入站,并且今天阻止部署。CLI 输出和 HCP Terraform 中的运行详细信息列出了哪些策略失败。
使用 HCP Terraform 中的策略,您可以防止 Terraform 创建违反您的基础设施和组织标准的资源。
在继续之前,修复您的策略和配置以允许成功应用。
导航到您的组织 Policy sets 页面,然后选择您的learn-terraform-drift-and-policy策略集。
滚动到页面底部,选择forbidden_days参数旁边的 ... 按钮,然后点击 Edit。将值设置为["Friday"](如果今天是星期五,则设置为另一个日期),然后点击 Save parameter。
恢复对modules/network/main.tf中aws_security_group.bastion资源的更改,使其反映您实际的基础设施配置。
resource "aws_security_group" "bastion" {
name = "bastion_ssh"
vpc_id = module.vpc.vpc_id
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["192.80.0.0/16"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
重新应用您的配置,使您的工作空间恢复到健康状态。
$ terraform apply
##...
No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no differences, so no
changes are needed.
Post-plan Tasks:
OPA Policy Evaluation
→→ Overall Result: PASSED
This result means that all policies passed and the protected behavior is allowed
2 policies evaluated
→ Policy set 1: learn-terraform-drift-and-policy-template (2)
↳ Policy name: friday_deploys
| ✓ Passed
| No description available
↳ Policy name: public_ingress
| ✓ Passed
| No description available
引入基础设施漂移
自定义条件、输入验证和策略实施有助于组织在资源预置时维护其标准。HCP Terraform 还可以检查 Terraform state 中的现有资源是否仍然与预期的配置匹配。
检测漂移
HCP Terraform 的自动健康评估有助于确保现有资源与其 Terraform 配置匹配。为此,HCP Terraform 会在配置的工作空间中运行非操作性的、仅刷新的计划,以将基础设施的实际设置与工作空间状态文件中跟踪的资源进行比较。评估不会更新您的状态或基础设施配置。
评估包括两种类型的检查,您可以同时启用它们。漂移检测确定资源是否在 Terraform 工作流之外发生了更改。健康检查验证您在配置中定义的任何自定义条件是否仍然有效,例如检查证书是否仍然有效。您可以在特定工作空间或整个组织的所有工作空间中启用评估。评估仅在上次应用成功的S工作空间上运行。如果上次应用失败,则工作空间已经需要操作员关注。在继续之前,请确保您的上次应用已成功。
在 HCP Terraform UI 中导航到您的learn-terraform-drift-and-policy工作空间。在工作空间的 Settings 下,选择 Health。
选择 Enable,然后点击 Save settings。
在第一次健康评估运行之前,您必须成功应用一次。再次应用您的配置。不会有任何更改。回复确认提示yes。
$ terraform apply
Running apply in HCP Terraform. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.
Preparing the remote apply...
To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-training/learn-terraform-drift-and-policy/runs/run-AvUG2EEkVqYsSyAh
Waiting for the plan to start...
Terraform v1.9.6
on linux_amd64
Initializing plugins and modules...
module.network.data.aws_availability_zones.available: Refreshing...
##...
module.network.module.vpc.aws_route_table.private[1]: Drift detected (update)
No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
Post-plan Tasks:
------------------------------------------------------------------------
Policy Evaluations
--------------------------------
Sentinel Policy Evaluation
→→ Overall Result: PASSED
This result means that all Sentinel policies passed and the protected behavior is allowed
2 policies evaluated
→ Policy set 1: learn-terraform-drift-and-policy (2)
↳ Policy name: friday_deploys.sentinel
| ✓ Passed
| No description available
↳ Policy name: public_ingress.sentinel
| ✓ Passed
| No description available
创建基础设施漂移
回到假设的生产事故,想象一下工程师试图通过在故障排除时手动更改资源来绕过策略。
要模拟此情况,请导航到 AWS console 中的安全组。
找到bastion_ssh安全组。在安全组详细信息中选择 Inbound rules 选项卡,然后点击 Edit inbound rules。删除192.168.0.0/16源 CIDR,并将其替换为0.0.0.0/0。然后,点击 Save rules。
您现在已通过在 Terraform 工作流之外管理安全组资源,向配置引入了基础设施漂移。
几分钟后,Terraform 将在工作空间概览页面上报告失败的评估。您也可以通过导航到工作空间的 Health 页面并点击 Start health assessment 按钮来手动触发评估。
点击 View Details 获取更多信息。HCP Terraform 检测到您的入站规则更改,并报告了如果您不更新配置,下次运行将会发生什么。
健康评估检测到基础设施漂移。这些检查确保您的基础设施配置仍然与编写的配置匹配,并满足任何定义的自定义条件,从而将您的验证覆盖范围扩展到预置时间之外。修复漂移是一个手动过程,因为您需要了解是否要保留在 Terraform 之外进行的基础设施更改,还是覆盖它们。在这种情况下,您可以运行另一个 Terraform apply 来覆盖安全组更新。
清理基础设施
销毁您作为本教程的一部分创建的资源,以避免产生不必要的成本。对提示回复yes以确认操作。
$ terraform destroy
Running apply in HCP Terraform. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.
Preparing the remote apply...
To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-training/learn-terraform-drift-and-policy/runs/run-8KX8K7T8TbshCmHw
Waiting for the plan to start...
Terraform v1.9.6
on linux_amd64
Initializing plugins and modules...
## ...
→→ Overall Result: PASSED
This result means that all Sentinel policies passed and the protected behavior is allowed
2 policies evaluated
→ Policy set 1: learn-terraform-drift-and-policy (2)
↳ Policy name: friday_deploys.sentinel
| ✓ Passed
| No description available
↳ Policy name: public_ingress.sentinel
| ✓ Passed
| No description available
Do you really want to destroy all resources in workspace "learn-terraform-drift-and-policy"?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes
## ...
module.network.module.vpc.aws_subnet.public[0]: Destruction complete after 1s
module.network.module.vpc.aws_subnet.public[1]: Destruction complete after 1s
module.network.aws_security_group.bastion: Destruction complete after 1s
module.network.module.vpc.aws_vpc.this[0]: Destroying... [id=vpc-0d297f5afc2209eab]
module.network.module.vpc.aws_vpc.this[0]: Destruction complete after 1s
Apply complete! Resources: 0 added, 0 changed, 25 destroyed.
(可选)从您的 HCP Terraform 组织中删除learn-terraform-drift-and-policy工作空间和策略集。
下一步
在本教程中,您使用了 Terraform 语言功能和 HCP Terraform 策略来确保您的基础设施与您的配置匹配,并符合您的组织需求和标准。配置级别的验证(例如前置条件)允许您在 Terraform 配置中指定标准。HCP Terraform 策略允许您为整个工作空间或组织强制执行标准。您还使用了 HCP Terraform 健康评估来确保现有基础设施仍然与 Terraform 配置匹配,并且没有在 Terraform 工作流之外发生更改。
要了解有关 Terraform 功能如何帮助您验证基础设施配置的更多信息,请查看以下资源:
查看策略文档。
了解如何配置和使用健康评估来检测基础设施漂移。
了解如何在 HCP Terraform 中管理基础设施成本。
了解如何使用 HCP Terraform 运行任务和 HCP Packer 来确保机器镜像合规性。
查看健康评估文档。