github中的Jenkinsfile和terraform模块:如何通过密钥进行身份验证?

时间:2020-07-27 13:08:19

标签: jenkins github jenkins-pipeline terraform ssh-keys

我有:

  • 带有Terraform12代码的主要github存储库
  • 二级仓库中的
  • 模块,称为source = "git@github.com:user/mod_repo?ref=v1.0.0"
  • Jenkins 2.249(现在无法更新)
  • Jenkins中的ssh私钥,用于访问mod_repo

当我尝试在Jenkins管道中运行terraform init时,我会得到

Could not download module "vpc" (main.tf:1) source code from
"git@github.com:user/mod_repo?ref=v1.0.0": error downloading
'ssh://git@github.com/user/mod_repo?ref=v1.0.0': /usr/bin/git exited
with 128: Cloning into '.terraform/modules/vpc'...
Permission denied (publickey).

在本地我可以毫无问题地做到这一点。 如何在Jenkinsfile *(或其他位置?)中配置密钥?允许访问辅助存储库?

我见过thisthisthisthis,但不知道如何将它们连接在一起。

1 个答案:

答案 0 :(得分:1)

您需要使用 sshagent 并将您的密钥传递给它,就像这样

sshagent (credentials: ['my-build-ssh-key']) {
    sh 'terraform init'
    withAWS(credentials: 'aws-build'){
        sh 'terraform apply -lock=false -auto-approve'
    }
}

应首先将密钥添加到 Jenkins 的凭据部分,然后名称将代替 my-build-ssh-key

这意味着当您运行 terraform init 时,它将有权在拉入模块时使用该密钥。

在该示例中,它还使用存储在 Jenkins 中的凭据以及此插件 (https://www.jenkins.io/doc/pipeline/steps/pipeline-aws/) 与 AWS 对话并启动您的堆栈。