首页 > 解决方案 > 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
}

标签: pythonamazon-ec2terraformgitlab-ci

解决方案


推荐阅读