Using Terraform 0.7.7.
I have a simple Terraform file with the following:
provider "aws" {
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
region = "${var.region}"
}
resource "aws_instance" "personal" {
ami = "${lookup(var.amis, var.region)}"
instance_type = "t2.micro"
}
resource "aws_eip" "ip" {
instance = "${aws_instance.personal.id}"
}
resource "aws_key_pair" "personal" {
key_name = "mschuchard-us-east"
public_key = "${var.public_key}"
}
Terraform apply
yields the following error:
aws_key_pair.personal: Creating...
fingerprint: "" => "<computed>"
key_name: "" => "mschuchard-us-east"
public_key: "" => "ssh-rsa pubkey hash mschuchard-us-east"
aws_instance.personal: Creating...
ami: "" => "ami-c481fad3"
availability_zone: "" => "<computed>"
ebs_block_device.#: "" => "<computed>"
ephemeral_block_device.#: "" => "<computed>"
instance_state: "" => "<computed>"
instance_type: "" => "t2.micro"
key_name: "" => "<computed>"
network_interface_id: "" => "<computed>"
placement_group: "" => "<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>"
vpc_security_group_ids.#: "" => "<computed>"
aws_instance.personal: Creation complete
aws_eip.ip: Creating...
allocation_id: "" => "<computed>"
association_id: "" => "<computed>"
domain: "" => "<computed>"
instance: "" => "i-0ab94b58b0089697d"
network_interface: "" => "<computed>"
private_ip: "" => "<computed>"
public_ip: "" => "<computed>"
vpc: "" => "<computed>"
aws_eip.ip: Creation complete
Error applying plan:
1 error(s) occurred:
* aws_key_pair.personal: Error import KeyPair: InvalidKeyPair.Duplicate: The keypair 'mschuchard-us-east' already exists.
status code: 400, request id: 51950b9a-55e8-4901-bf35-4d2be234abbf
The only help I found with googling was to blow away the *.tfstate
files, which I tried and that did not help. I can launch an EC2 instance with the gui with this key pair and easily ssh into it, but Terraform is erroring when trying to use the same fully functional keypair.
The error is telling you that the keypair already exists in your AWS account but Terraform has no knowledge of it in its state files so is attempting to create it each time.
You have two options available to you here. Firstly, you could simply delete it from the AWS account and allow Terraform to upload it and thus allow it to be managed by Terraform and be in its state files.
Alternatively you could use the Terraform import
command to import the pre-existing resource into your state file:
terraform import aws_key_pair.personal mschuchard-us-east