How can I load my AWS EC2 Key pair PEM file to my terratest script to perform AWS EC2 SSH connection validation

379 views Asked by At

I am writing Go terratest script to validate SSH connection for AWS EC2 instance

I already have AWS EC2 keypair PEM file in my local

I am able to launch and destroy EC2 instance using terraform.TgApplyAll() and terraform.TgDestroyAll() methods and fetch the output variables using terraform.Output() method

My local AWS EC2 keypair PEM file is used for creating EC2 instance in AWS

Now I am trying to validate SSH connection Programmatically from terratest Go script.

I am NOT able to load my local AWS EC2 Key pair to sshKeyPair variable in Go terratest script

I used below code snippet but no use

https://github.com/gruntwork-io/module-asg/blob/067647b3aaeb24151badbc5a2d9a6b5381dd2041/test/server_group_test.go#L78

I also tried script present in at https://github.com/gruntwork-io/terratest/blob/907c09f0696083a5ada580debb66bb5c00c19c32/modules/test-structure/save_test_data.go#L66 to load my local EC2 key pair using LoadEc2KeyPair and test EC2 SSH using fmt.Sprintf("SSH to public host %s", publicIP) But getting error while reading EC2 keypair from local in LoadTestData(t testing.TestingT, path string, value interface{}) method at json.Unmarshal(bytes, value) built in call

Error message : Failed to parse JSON for value D:\AWS\KeyPair\pandukeypair.pem: invalid character '-' in numeric literal I am getting this error as I am trying to ream .pem file and code is trying to do json.umarshal on the .pem file

All code snippets available in github/terratest modules talks about creating new keypair and loading AWS EC2 JSON keypair as but i am not getting any approach/Logic for my scenario where already existing keypair JSON is present I just want to load and use it.

Full Code is present in below link

https://www.dropbox.com/sh/dl2mpesidsxitdu/AAAOi4Nmp41CHMSPcyU7a2qva?dl=0

1

There are 1 answers

0
Sanjay  Gayakwad On BEST ANSWER

This can be achieved by using below Code snippet/functio ..

GenerateRSAKeyPairE: func RSAKeyPairFromFile(fpath string) (*terrassh.KeyPair, error) { // import crypto/x509 // import enter code hereio/ioutil // import encoding/pem // import "golang.org/x/crypto/ssh" // terrassh "github.com/gruntwork-io/terratest/modules/ssh"

pemBytes, err := ioutil.ReadFile(fpath)
if err != nil {
    return nil, err
}
pemBlock, _ := pem.Decode(pemBytes)
if pemBlock == nil {
    return nil, fmt.Errorf("failed to decode PEM block containing private key")
}
privKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
if err != nil {
    return nil, err
}
sshPubKey, err := ssh.NewPublicKey(privKey.Public())
if err != nil {
    return nil, err
}
sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)
sshPubKeyStr := string(sshPubKeyBytes)
return &terrassh.KeyPair{PublicKey: sshPubKeyStr, PrivateKey: string(pemBytes)}, nil

}