익명 14:22

Terraform error: importing EC2 Key Pair (XXXX): InvalidKeyPair.Duplicate: The ke...

Terraform error: importing EC2 Key Pair (XXXX): InvalidKeyPair.Duplicate: The keypair already exists

Terraform newbie here. I am trying to add an additional node group to existing terraform stack that has already been deployed in AWS region by someone else in my organization. I have run through the setup and I have edited the terraform.tf file to include my additional node group. When I come to apply I run into:-

│ Error: importing EC2 Key Pair (XXXXX): InvalidKeyPair.Duplicate: The keypair already exists
│       status code: 400, request id:XXXXXX-XXXX-XXXXX-XXXX-XXXXXX
│
│   with module.networks.aws_key_pair.user,
│   on modules\networks\ec2.tf line 1, in resource "aws_key_pair" "user":
│    1: resource "aws_key_pair" "user" {

Things I checked / tried:-

  • That the AWS key pairs XXXXX is in my console and there is no duplicates.

  • Tried the "terraform import" cmd with name | ID from the console but this draws me into a series of questions e.g. Regions, AZs that are already detailed in my script.

  • Hardwiring my file modules\networks\ec2.tf with the key name and public key(rsa...)

Still not got me cigar so would welcome any suggestions



Top Answer/Comment:

As the error mentions the "The keypair already exists". However Terraform is not aware of it's existence and it's attempting to create it.

There's few things one can do here:

  • Ensure you have the correct Terraform state. If Terraform was used to deployed this resource properly it should be in the state. It could be either state configurations are wrong, some other state is being used by accident or perhaps you don't have the state file.

  • If it's not in state, state was lost for any reason or importing missing resource is easier into new state, then you can import it into the state. The documentation mentions that the keypair can simply be imported by it's key_name. For example if the key name is XXXXX per the question then it can be imported with:

    $ terraform import aws_key_pair.user XXXXX
    

Region doesn't need to specified in the import command as it specified by the AWS provider configuration or the credentials. Although it would be good to double check those before accidentally deploying into the wrong envrionment!

상단 광고의 [X] 버튼을 누르면 내용이 보입니다