【问题标题】:How can I load my AWS EC2 Key pair PEM file to my terratest script to perform AWS EC2 SSH connection validation如何将我的 AWS EC2 密钥对 PEM 文件加载到我的 terratest 脚本以执行 AWS EC2 SSH 连接验证
【发布时间】:2021-03-23 00:31:06
【问题描述】:

我正在编写 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 变量

我用下面的代码sn-p但是没用

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

我还尝试了出现在 at 的脚本 https://github.com/gruntwork-io/terratest/blob/907c09f0696083a5ada580debb66bb5c00c19c32/modules/test-structure/save_test_data.go#L66 使用 LoadEc2KeyPair 加载我的本地 EC2 密钥对并使用 fmt.Sprintf("SSH to public host %s", publicIP) 测试 EC2 SSH 但是在 json.Unmarshal(bytes, value)LoadTestData(t testing.TestingT, path string, value interface{}) 方法中从本地读取 EC2 密钥对时出错通话中

错误信息: 无法为值 D:\AWS\KeyPair\pandukeypair.pem 解析 JSON:数字文字中的无效字符“-” 我在尝试读取 .pem 文件时遇到此错误,并且代码尝试在 .pem 文件上执行 json.umashal

github/terratest 模块中可用的所有代码 sn-ps 都谈到了创建 new 密钥对和加载 AWS EC2 JSON 密钥对,但我没有得到任何方法/逻辑我的场景中已经存在 existing 密钥对 JSON 我只想加载和使用它。

完整的代码在下面的链接中

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

【问题讨论】:

  • 几个术语 cmets: 1. 语言称为“Go”,而不是“GoLang”。 2. 没有“Go 脚本”之类的东西,因为 Go 是编译的,而脚本,根据定义,是被解释的。
  • 除此之外,您的问题不完整。您提供了一些我们看不到的代码的链接。即使我们可以看到它,所有相关代码也必须在问题中,因为链接往往会变坏。
  • 重现问题的代码。这就是这些东西的意义
  • 你可以分享你的 _test.go 文件的 ssh 测试代码吗?

标签: go amazon-ec2 terraform key-pair terratest


【解决方案1】:

这可以通过使用下面的代码来实现 sn-p/functio ..

生成RSAKeyPairE: func RSAKeyPairFromFile(fpath string) (*terrassh.KeyPair, error) { // 导入加密/x509 // 导入enter code hereio/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

}

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 2020-01-10
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多