登录
首页 >  Golang >  Go问答

使用 terratest 脚本加载 AWS EC2 SSH 密钥对 PEM 文件并进行连接验证的步骤

来源:stackoverflow

时间:2024-02-14 19:06:24 266浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《使用 terratest 脚本加载 AWS EC2 SSH 密钥对 PEM 文件并进行连接验证的步骤》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在编写 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-struct/save_test_data.go#L66 使用 LoadEc2KeyPair 加载我的本地 EC2 密钥对并使用 fmt.Sprintf( “SSH 到公共主机 %s”,publicIP) 但是在 json.Unmarshal(bytes, value) 构建的 LoadTestData(t testing.TestingT, path string, value interface{}) 方法中从本地读取 EC2 密钥对时出现错误通话中

错误消息: 无法解析 JSON 值 D:\AWS\KeyPair\pandukeypair.pem:数字文本中的字符“-”无效 当我尝试扩容 .pem 文件并且代码尝试在 .pem 文件上执行 json.umarshal 时,我收到此错误

github/terratest模块中可用的所有代码片段都讨论了创建密钥对和加载AWS EC2 JSON密钥对,但我没有为我的场景获得任何方法/逻辑如果已经存在现有密钥对 JSON,我只想加载并使用它。

完整代码位于以下链接

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


解决方案


这可以通过使用下面的代码片段/函数来实现..

生成rsa密钥对e: func rsakeypairfromfile(fpath string) (*terrassh.keypair, error) { // 导入加密/x509 // 在这里导入enter代码io/ioutil // 导入编码/pem // 导入“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

}

今天关于《使用 terratest 脚本加载 AWS EC2 SSH 密钥对 PEM 文件并进行连接验证的步骤》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>