Terraform ec2-instance keypair, SSH: access denied <public key>

Hi, I wonder if you can help with this example -----

resource “aws_key_pair” “auth” {
key_name = “key1”
public_key = file(“key.pub”) #file in terraform folder Or
}

resource “aws_instance” “terraform_instance” {
ami = “ami-062dbd29edfdac661”
instance_type = “t2.micro”
key_name = aws_key_pair.key1.public_key Or
key_name = aws_key_pair.key1.auth.public_key Or
key_name = “key1” Or
key_name = file(“id_rsa.pub”) #public key Or
key_name = file(“id_rsa”) #private key #None allows ssh access
vpc_security_group_ids = [aws_security_group.allow_ssh.id]
subnet_id = aws_subnet.my_subnet.id
associate_public_ip_address = true
source_dest_check = false

tags = {
Name = “tf_instance”
}
}

The EC2 instance builds and answers SSH, but provides access denied. E.g.
ssh -i publickey user@ip-address Or
ssh -i privatekey user@ip-address Or
ssh -i publickey ip-address Or
ssh -i privatekey ip-address #As above no access is allowed.

Can you advise, where I’m going wrong? Thanks.

in the aws_instance you will need to use: aws_key_pair.auth.key_name

ref: https://www.terraform.io/docs/providers/aws/r/key_pair.html#key_name-1

for ssh, you have to use:
ssh -i key.pem username@ip-address

the “key.pem” is the private key of the key.pub that you supplied in the aws_key_pair resource.

HTH,
Shantanu Gadgil

EDIT: added username

If is definitely: ssh -i key.pem username@ipaddress
. This will help to know. Thanks.

I have tried “.auth.key_name” also :slight_smile:

what type of OS is “ami-062dbd29edfdac661”?

Amazon Linux uses ec2-user
CentOS uses centos
Ubuntu uses ubuntu

Edit: for -i try specifying full path to the private key files.
also can you confirm permissions of the private key file? (they should be 0600)

Do you know, with: ssh -i key.pem username@ip-address how to specify a different username than the ami username for the keypair?

Also, how to specify individual SSH username and password without using ssh keypairs?

Thanks.