为了账号安全,请及时绑定邮箱和手机立即绑定

如何将我的 AWS EC2 密钥对 PEM 文件加载到我的 terratest 脚本以执行

如何将我的 AWS EC2 密钥对 PEM 文件加载到我的 terratest 脚本以执行

Go
呼如林 2022-07-18 17:19:08
我正在编写 Go terratest 脚本来验证 AWS EC2 实例的 SSH 连接我的本地已经有 AWS EC2 密钥对 PEM 文件我能够使用 terraform.TgApplyAll() 和 terraform.TgDestroyAll() 方法启动和销毁 EC2 实例,并使用 terraform.Output() 方法获取输出变量我的本地 AWS EC2 密钥对 PEM 文件用于在 AWS 中创建 EC2 实例现在我正在尝试从 terratest Go 脚本以编程方式验证 SSH 连接。我无法将本地 AWS EC2 密钥对加载 到 Go terratest 脚本中的sshKeyPair变量我使用了下面的代码片段但没有用https://github.com/gruntwork-io/module-asg/blob/067647b3aaeb24151badbc5a2d9a6b5381dd2041/test/server_group_test.go#L78我还尝试了 https://github.com/gruntwork-io/terratest/blob/907c09f0696083a5ada580debb66bb5c00c19c32/modules/test-structure/save_test_data.go#L66中的脚本 来使用 LoadEc2KeyPair 加载我的本地 EC2 密钥对并使用测试 EC2 SSH fmt.Sprintf("SSH to public host %s", publicIP)但是在json.Unmarshal(bytes, value)的LoadTestData(t testing.TestingT, path string, value interface{})方法中 从本地读取 EC2 密钥对时出错内置调用错误消息:无法为值 D:\AWS\KeyPair\pandukeypair.pem 解析 JSON:数字文字中的无效字符 '-' 当我尝试读取 .pem 文件并且代码尝试执行 json 时,我收到此错误。 .pem 文件上的元帅github/terratest 模块中可用的所有代码片段都讨论了创建新的密钥对和加载 AWS EC2 JSON密钥对,但我没有得到任何方法/逻辑,因为我的场景已经存在现有的密钥对 JSON,我只想加载和使用它。完整代码在下面的链接中https://www.dropbox.com/sh/dl2mpesidsxitdu/AAAOi4Nmp41CHMSPcyU7a2qva?dl=0
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

这可以通过使用下面的代码片段/功能来实现。


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

}


查看完整回答
反对 回复 2022-07-18
  • 1 回答
  • 0 关注
  • 204 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号