'I can not ssh to newly created ec2 instance within terraform

I can not ssh to my newly created ec2 instance using terraform

Keep getting permission denied (publickey)

I generated the key using ssh-keygen -t rsa command

Please help me get this through this error

ssh -i ~/.ssh/ubuntu/mykey [email protected]

Root/main.tf , here I defined it then passed t the variable.tf

module "compute" {
  source          = "./compute"
  instance_count  = 1
  instance_type   = "t3.micro"
  public_sg       = module.networking.public_sg
  public_subnets  = module.networking.public_subnets
  vol_size        = 10
  public_key_path = "/home/ubuntu/.ssh/mykey.pub"
  key_name        = "mykey"
  user_data_path = "${path.root}/userdata.tpl"
  db_endpoint     = module.database.db_endpoint
  dbuser          = var.dbuser
  dbpassword          = var.dbpassword
  dbname          = var.dbname

}

Compute main.tf , referrenced to my instance

resource "aws_key_pair" "my_key" {
  key_name   = var.key_name
  public_key = file(var.public_key_path)
}

resource "aws_instance" "my_instance" {
  count         = var.instance_count
  instance_type = var.instance_type
  ami           = data.aws_ami.server_ami.id

  tags = {
    Name = "my-node ${random_id.random[count.index].dec}"
  }

  key_name               = aws_key_pair.my_key.id
  vpc_security_group_ids = [var.public_sg]
  subnet_id              = var.public_subnets[count.index]
  user_data = templatefile(var.user_data_path,
    {
      nodename    = "my-node ${random_id.random[count.index].dec}"
      db_endpoint = var.db_endpoint
      dbuser      = var.dbuser
      dbpass      = var.dbpassword
      dbname      = var.dbname
    }
  )

  root_block_device {
    volume_size = var.vol_size
  }
}

Variable.tf which passed over the root/main.tf

variable "instance_count" {}
variable "instance_type" {}
variable "vol_size" {}
variable "public_sg" {}
variable "public_subnets" {}
variable "public_key_path" {}
variable "key_name" {}
variable "db_endpoint" {}
variable "dbname" {}
variable "dbpassword" {}
variable "dbuser" {}
variable "user_data_path" {}


Solution 1:[1]

 key_name               = aws_key_pair.my_key.key_name

I think i had the same issue as well. this one fixed it. It should be 'key_name' and not 'id'

btw, you are using the variables , which improves reusability of the code for different configuration.

Cheers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BBM