Terraform apply fails in remote-exec failed to read ssh private key, no key found

Hello, I’m getting Failed to read ssh private key, no key found in Provisioner Connection but I’m able to ssh manually using the same private key.

Note*** creating a new key_pair works but the task is to use existing key in AWS. Thanks

provisioner "remote-exec" {
   connection {
     host  = self.private_ip
     user  = "ec2-user"
     type  = "ssh"
     private_key  = aws_instance.jenkins_rebuild.key_name
   }

also, tried “private_key = self.key_name” but still getting the same error. Thanks

Hi @ndario91,

The key_name attribute of an aws_instance object is the symbolic name of a key pair as used with the AWS API.

The remote-exec provisioner doesn’t know anything about AWS, so it needs the actual private key material in PEM format, not just a reference to the keypair in AWS. That information is not available as an attribute of aws_instance (the EC2 API doesn’t actually know your private key, only the associated public key), so you’ll need to find some other way to provide the key material to Terraform.

Provisioners are a last resort, in large part because of all of this complexity of setting up connectivity and keys correctly. I strongly suggest trying to use one of the alternatives mentioned in the documentation, and avoiding using provisioners at all unless you have absolutely no other option.