python - Terraform 销毁不会终止 ec2 实例
问题描述
我目前有一个 Gitlab Runner,它将执行一个 shell 脚本,该脚本运行 Terraform apply 并在 AWS 中创建一个 EC2 实例。在某些情况下,EC2 可能/将无法成功初始化,在这种情况下,我们要删除资源。尝试运行 Terraform destroy 时,我似乎无法成功删除未能创建的资源。我试过从不同的目录运行destroy命令会不走运。在正确的方向上寻找任何帮助:)
外壳脚本:
cd terraform
terraform init
terraform plan -out plan.tfplan
terraform apply -auto-approve -input=false plan.tfplan
new_instance_id=$(terraform state pull aws_instance.create_clone | jq '. | .resources[0].instances[0].attributes.id' | tr -d '"')
python3 ../tests/instance_status.py $new_instance_id
检查实例状态并运行 Terraform destroy 的 instane_status.py 脚本的结尾:
if "failed" or "insufficient-data" in status_results:
print("The instance has failed to create successfully. System logs will be saved and Terraform Destroy will be run.")
system_logs = client.get_console_output(
InstanceId=new_instance_id,
)
system_logs_json = json.dumps(system_logs, default=str)
with open('sys_logs.json', 'w+') as f:
f.write(system_logs_json)
subprocess.run(["terraform", "plan", "--destroy"], shell=True)
subprocess.run(["terraform", "destory", "-auto-approve", "-target=plan.tfplan"], shell=True)
Gitlab 中的最后一点输出:
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
This plan was saved to: plan.tfplan
To perform exactly these actions, run the following command to apply:
terraform apply "plan.tfplan"
aws_instance.create_clone: Creating...
aws_instance.create_clone: Still creating... [10s elapsed]
aws_instance.create_clone: Still creating... [20s elapsed]
aws_instance.create_clone: Creation complete after 21s [id=[REDACTED]]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.
State path: terraform.tfstate
Usage: terraform [-version] [-help] <command> [args]
The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.
Common commands:
apply Builds or changes infrastructure
console Interactive console for Terraform interpolations
destroy Destroy Terraform-managed infrastructure
env Workspace management
fmt Rewrites config files to canonical format
get Download and install modules for the configuration
graph Create a visual graph of Terraform resources
import Import existing infrastructure into Terraform
init Initialize a Terraform working directory
login Obtain and save credentials for a remote host
logout Remove locally-stored credentials for a remote host
output Read an output from a state file
plan Generate and show an execution plan
providers Prints a tree of the providers used in the configuration
refresh Update local state file against real resources
show Inspect Terraform state or plan
taint Manually mark a resource for recreation
untaint Manually unmark a resource as tainted
validate Validates the Terraform files
version Prints the Terraform version
workspace Workspace management
All other commands:
0.12upgrade Rewrites pre-0.12 module source code for v0.12
0.13upgrade Rewrites pre-0.13 module source code for v0.13
debug Debug output management (experimental)
force-unlock Manually unlock the terraform state
push Obsolete command for Terraform Enterprise legacy (v1)
state Advanced state management
Usage: terraform [-version] [-help] <command> [args]
The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.
Common commands:
apply Builds or changes infrastructure
console Interactive console for Terraform interpolations
destroy Destroy Terraform-managed infrastructure
env Workspace management
fmt Rewrites config files to canonical format
get Download and install modules for the configuration
graph Create a visual graph of Terraform resources
import Import existing infrastructure into Terraform
init Initialize a Terraform working directory
login Obtain and save credentials for a remote host
logout Remove locally-stored credentials for a remote host
output Read an output from a state file
plan Generate and show an execution plan
providers Prints a tree of the providers used in the configuration
refresh Update local state file against real resources
show Inspect Terraform state or plan
taint Manually mark a resource for recreation
untaint Manually unmark a resource as tainted
validate Validates the Terraform files
version Prints the Terraform version
workspace Workspace management
All other commands:
0.12upgrade Rewrites pre-0.12 module source code for v0.12
0.13upgrade Rewrites pre-0.13 module source code for v0.13
debug Debug output management (experimental)
force-unlock Manually unlock the terraform state
push Obsolete command for Terraform Enterprise legacy (v1)
state Advanced state management
The instance has failed to create successfully. System logs will be saved and Terraform Destroy will be run.
Cleaning up file based variables
00:00
Job succeeded
主文件:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.20"
}
}
}
provider "aws" {
region = "us-west-1"
}
resource "aws_instance" "create_clone" {
ami = var.amiId
instance_type = var.instancetype
vpc_security_group_ids = var.sglist
subnet_id = var.subnetid
iam_instance_profile = var.iamrole
key_name = var.keypair
tags = var.clean_tags
}
变量.tf:
variable "amiId" {
description = "AMI Id used to create the new EC2 instance."
type = string
}
variable "instancetype" {
description = "Instance type used to create the new EC2 instance."
type = string
}
variable "subnetid" {
description = "Subnet used to create the new EC2 instance."
type = string
}
variable "sglist" {
description = "List of Security Groups that need to be added to the new EC2 instance."
type = list(string)
}
variable "iamrole" {
description = "IAM role used to create the new EC2 instance."
type = string
default = "Terraform-common"
}
variable "keypair" {
description = "Key Pair used to create the new EC2 instance."
type = string
default = "[REDACTED]"
}
variable "clean_tags" {
description = "List of tags that need to be added to the new EC2 instance."
type = map
}
解决方案
推荐阅读
- spring - SecurityContextHolder.getContext().getAuthentication() 从 @ControllerAdvice 类调用时返回 null
- python - 如何使用 for range 循环遍历 Python 中的两个列表?
- bash - 启用 bash-completion 会禁用自动完成文件名的默认行为
- node.js - Nodejs - 使用预签名的 url 从 s3 存储桶反应下载文件
- ruby-on-rails - 在 Rails 中使用 Pundit 限制整个控制器的 DRY 方法是什么?
- python - 当数据限制不同时创建具有多个轴的等宽(正方形)图?
- azure-service-fabric-mesh - 如何在 Azure 服务结构网格中为 Asp.net 核心应用程序启用 TLS SSL Https
- python - sqlalchemy 核心中的自引用列
- python-2.7 - 将偏移量转换为非偏移量的 Python 日期
- compiler-errors - 为什么我不能将 main.rs 添加到 crate 的源代码并导入结构?