使用一个 .tf 文件(其中包括创建 s3 存储桶、ec2 和安全组),我担心的是,如果我运行 terraform apply 并且它在中间中止后成功创建了 s3 存储桶。 在上面的情况下,我想回滚 terraform apply 运行后发生的所有更改。
一旦 .tf 文件开始运行,我就中止该进程,但更改不会回滚。
provider "aws" { }
resource "aws_instance" "example" {
ami = "ami-2757f631"
instance_type = "t2.micro"
}
resource "aws_s3_bucket" "b" {
bucket = "my-tf-test-bucket"
acl = "private"
tags = {
Name = "My bucket"
Environment = "Dev"
}
}
resource "aws_security_group" "allow_rdp" {
name = "allow_rdp"
description = "Allow rdp traffic"
ingress {
from_port = 3389 # By default, the windows server listens on TCP port 3389 for RDP
to_port = 3389
protocol = "tcp"
}
}
如果您使用 git 并保留最后一次已知的导致 terraform 应用成功的 git 提交,您可以执行以下操作:
# Apply Terraform configuration
echo "Applying Terraform..."
if terraform apply -auto-approve; then
echo "Terraform applied successfully."
else
echo "Terraform apply failed. Rolling back to last successful commit: $last_successful_commit"
git checkout $last_successful_commit
# Optionally, you might want to reinitialize Terraform if your configurations depend on different modules/providers
terraform init
# Apply Terraform configuration again
if terraform apply -auto-approve; then
echo "Terraform rollback back."
else
echo "Terraform rollback failed."
fi
fi
当然这并不适用于所有情况。最好在应用之前了解一下资源更新的性质,看看什么样的更新可以安全回滚。