首页 > 解决方案 > Terrafrom AWS EC2 没有更改代码,尝试销毁和创建实例

问题描述

我使用下面的 terrafrom 代码创建 AWS EC2 实例,

resource "aws_instance" "example" {
  ami             = var.ami-id
  instance_type   = var.ec2_type
  key_name        = var.keyname
  subnet_id       = "subnet-05a63e5c1a6bcb7ac"
  security_groups = ["sg-082d39ed218fc0f2e"]

  # root disk
  root_block_device {
    volume_size           = "10"
    volume_type           = "gp3"
    encrypted             = true
    delete_on_termination = true
  }

  tags = {
    Name        = var.instance_name
    Environment = "dev"
  }

  metadata_options {
    http_endpoint               = "enabled"
    http_put_response_hop_limit = 1
    http_tokens                 = "required"
  }

}

5 分钟后,当我尝试运行时代码没有任何变化terraform plan。它显示了 Terraform 之外的一些变化,它试图破坏并重新创建Ec2 实例。为什么会这样?

如何防止这种情况?

aws_instance.example: Refreshing state... [id=i-0aa279957d1287100]

Note: Objects have changed outside of Terraform

Terraform detected the following changes made outside of Terraform since the last "terraform apply":

  # aws_instance.example has been changed
  ~ resource "aws_instance" "example" {
        id                                   = "i-0aa279957d1287100"
      ~ security_groups                      = [
          - "sg-082d39ed218fc0f2e",
        ]
        tags                                 = {
            "Environment" = "dev"
            "Name"        = "ec2linux"
        }
        # (26 unchanged attributes hidden)





      ~ root_block_device {
          + tags                  = {}
            # (9 unchanged attributes hidden)
        }
        # (4 unchanged blocks hidden)
    }

Unless you have made equivalent changes to your configuration, or ignored the relevant attributes using ignore_changes, the following plan may include actions to undo or respond to these
changes.

─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

添加图像: 在此处输入图像描述

在此处输入图像描述

标签: terraformterraform-provider-aws

解决方案


您必须使用vpc_security_group_ids而不是security_groups

resource "aws_instance" "example" {
  ami             = var.ami-id
  instance_type   = var.ec2_type
  key_name        = var.keyname
  subnet_id       = "subnet-05a63e5c1a6bcb7ac"
  vpc_security_group_ids = ["sg-082d39ed218fc0f2e"]

  # root disk
  root_block_device {
    volume_size           = "10"
    volume_type           = "gp3"
    encrypted             = true
    delete_on_termination = true
  }

  tags = {
    Name        = var.instance_name
    Environment = "dev"
  }

  metadata_options {
    http_endpoint               = "enabled"
    http_put_response_hop_limit = 1
    http_tokens                 = "required"
  }

}

推荐阅读