使用声明性流水线中的Jenkins凭据进行Git推送

10

我正在使用Jenkins pipeline(声明性语法),我想将提交推送到我的远程代码库。

是否有一种方法可以使用git插件来实现这一目标? 下面是我目前尝试的方法:

withCredentials([usernamePassword(credentialsId: "${GIT_CREDENTIAL_ID}", passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                        sh "git add ${BRANCH_RENAME}.bundle"
                        sh "echo ${GIT_USERNAME}|||||||${GIT_PASSWORD}"
                        sh "git tag -a backup -m 'Backup branch ${BRANCH} from vega-salesforce to vega-salesforce-backup' "
                        sh('git push https://${GIT_USERNAME}:${GIT_PASSWORD}@${GIT_URL_WITHOUT_HTTPS} --tags')
                    }


但它不起作用。我收到以下错误:
fatal: unable to access 'https://****:****@myrepositoryurl/mygitgroup/salesforce-backup/': Could not resolve host: ****:clear_password_here; Name or service not known

请问有人能帮忙吗? 我认为问题可能是由于密码中存在特殊字符,但不确定。


这可能会更容易使用Git Pipeline插件。 - Matt Schuchard
Jenkins pipeline中没有git插件可以进行push操作。有吗? - Géraud Willing B-S
我们通过对密码进行URL编码来解决了这个问题。问题在于GIT_PASSWORD包含应该被编码的特殊字符。 - Géraud Willing B-S
2个回答

11
我们终于解决了问题。所遇到的问题仅是我们的密码中有特殊字符,这会导致url出现错误。
以下是可用的代码:
withCredentials([usernamePassword(credentialsId: env.GIT_CREDENTIAL_ID, usernameVariable: 'USER', passwordVariable: 'PASS')]) {
                    script {
                        env.encodedPass=URLEncoder.encode(PASS, "UTF-8")
                    }
                    sh 'git clone https://${USER}:${encodedPass}@${GIT_URL} ${DIR} -b ${BRANCH}'
                    sh 'git add .'
                    sh 'git commit -m "foobar" '
                    sh 'git push'
                } 

我认为这个解决方案只有一个问题。在您编码密码之后,jenkins将输出其值而不使用掩码(****)。 解决此问题的一种可能的解决方案是禁用命令回显。 我看到的另一个解决方案是[使用MaskPasswords插件](https://dev59.com/87joa4cB1Zd3GeqPAYop#59680266),但我不知道它是否有效,因为我无法测试它。 - Pedro Pinheiro
@PedroPinheiro,感谢您指出这一点! - Géraud Willing B-S

1

在脚本中连接git仓库时,不能使用用户名:密码。

您应该使用ssh密钥。有关更多信息,请参见this answer


1
由于公司限制,我无法使用ssh。 - Géraud Willing B-S
我们通过对密码进行URL编码来解决了这个问题。问题在于GIT_PASSWORD包含应该被编码的特殊字符。 - Géraud Willing B-S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接