Terraform执行plan显示将创建2个资源而非1个的问题咨询
解决Terraform Plan显示创建2个资源而非预期1个的问题
嘿,我来帮你捋清楚这个问题~你之前销毁实例后,现在执行terraform plan出现要创建2个资源的情况,核心原因是你的Terraform配置里同时定义了aws_instance.example和aws_key_pair.deployer两个资源,而且之前执行terraform destroy时,这两个资源都被销毁了——现在重新执行plan,Terraform会按照配置重新创建它们。
下面是具体的排查和解决步骤:
1. 检查你的Terraform配置文件
先打开你的.tf配置文件,确认是否存在aws_key_pair.deployer的资源定义,比如类似这样的代码块:
resource "aws_key_pair" "deployer" { key_name = "key-pair" public_key = "XXX" }
- 如果这个密钥对是你手动在AWS控制台创建的,并不想通过Terraform管理,那直接把这个
aws_key_pair资源块从配置里删掉,再重新执行terraform plan,就只会创建EC2实例了。 - 如果这个密钥对确实需要Terraform管理,但你希望复用之前的(而非重新创建),先去AWS控制台的EC2密钥对页面确认"key-pair"是否还存在:
- 如果已经被销毁了,那重新创建是正常的;
- 如果还存在,说明之前的
terraform destroy没处理它,或者状态文件有问题,你可以用terraform import命令把现有密钥对导入Terraform状态:
导入后再执行terraform import aws_key_pair.deployer key-pairterraform plan,就只会创建EC2实例了。
2. 验证Terraform状态
检查本地的terraform.tfstate文件,确认里面是否有残留的资源记录。如果terraform destroy执行成功,状态文件里应该是空的(或仅包含provider配置)。如果有残留,可以手动清理状态文件,或者执行terraform state rm命令删除多余的状态条目。
附:你提供的Plan输出
C:\terraform>terraform plan Refreshing Terraform state in-memory prior to plan... The refreshed state will be used to calculate this plan, but will not be persisted to local or remote state storage. ------------------------------------------------------------------------ An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: + aws_instance.example id: <computed> ami: "ami-051f75c651d856381" arn: <computed> associate_public_ip_address: <computed> availability_zone: <computed> cpu_core_count: <computed> cpu_threads_per_core: <computed> ebs_block_device.#: <computed> ephemeral_block_device.#: <computed> get_password_data: "false" host_id: <computed> instance_state: <computed> instance_type: "t2.micro" ipv6_address_count: <computed> ipv6_addresses.#: <computed> key_name: <computed> network_interface.#: <computed> network_interface_id: <computed> password_data: <computed> placement_group: <computed> primary_network_interface_id: <computed> private_dns: <computed> private_ip: <computed> public_dns: <computed> public_ip: <computed> root_block_device.#: <computed> security_groups.#: <computed> source_dest_check: "true" subnet_id: <computed> tenancy: <computed> volume_tags.%: <computed> vpc_security_group_ids.#: <computed> + aws_key_pair.deployer id: <computed> fingerprint: <computed> key_name: "key-pair" public_key: "XXX" Plan: 2 to add, 0 to change, 0 to destroy.
内容的提问来源于stack exchange,提问作者Sheik Kalidh
相关产品推荐
相关产品推荐

