Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

provisioning an EC2 instance with terraform InvalidKeyPair.NotFound

I've created a key pair for EC2 called terraform, downloaded the pem file to the same directory where my terraform files live, I issue a terraform apply and I get:

aws_instance.windows: Creating...

Error: Error launching source instance: InvalidKeyPair.NotFound: The key pair 'terraform' does not exist
        status code: 400, request id: 1ac563d4-244a-4371-bde7-ee9bcf048830

I'm specifying the name of the key-value pair via an envrionment variable. This is the start of the block I'm using to create the Windows virtual machine:

resource "aws_instance" "windows" {
  ami                         = data.aws_ami.Windows_2019.image_id
  instance_type               = var.windows_instance_types
  key_name                    = var.key_name
  vpc_security_group_ids      = [aws_security_group.allow_rdp_winrm.id]
  associate_public_ip_address = true
  subnet_id                   = aws_subnet.subnet1.id
  get_password_data           = "true"

  user_data = file("scripts/user_data.txt")

There is obviously something I'm doing wrong, do I need to tell terraform which aws region then key pair resides in ?

like image 784
ChrisAdkin Avatar asked Oct 21 '25 14:10

ChrisAdkin


1 Answers

The key pairs are regional, so if you created them in one region, they aren't available in the other.

Terraform will always try to find and use the key in the region that you tell it to run in and if the key is not present, AWS will complain about this error.

Terraform also doesn't like it when things are created out of band and you might run into complications. It's also much cleaner to create the keypair using terraform and you can reference it as Atul has posted in his answer.

You could also import the key into Terraform or use Terraform's data sources to search and find the key as alternatives but these are a bit advanced, especially if you're getting started with Terraform.

like image 184
Sathyajith Bhat Avatar answered Oct 23 '25 07:10

Sathyajith Bhat