有时有这种需求: pipeline 结束后,有新生成或被改动的文件,需要把这些变化check in 到 remote github repository中,其实就是git add/commit/push 操作。这在Jenkins中如何实现呢?
注意这里的Github repository is secured, 比如Github Enterprise。一般我们设置SSH credentials access (SSH Username with private key), 这个credential 会提前写到 Jenkins Credential Management中,在配置pipeline的时候,最后一步设置SCM -> Git, 除了输入Reporsity URL, 还要add SSH credential. 这样Jenkins才能正常地check out code. 当然,在pipeline steps 中 check out code也行,比如使用 git
, checkout
snippets.
对于check in code, 也可以使用snippet 比如:
-
withCredentials
Bind credential to variables, 这个snippet 可以提供通过环境变量访问credential. 但在这里对于git SSH credential access, 需要设置让git去使用这个变量,this is unknown to me. -
sshagent
: 需要install plugin: https://plugins.jenkins.io/ssh-agent/, pass credential to it. 然后把git 操作放在这个snippet中即可. 比如:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23steps {
sshagent(['<credential id>']) {
// fetch a branch, edit and check in the code
sh '''
## or git pull other repository
git fetch
git checkout $TARGET_BRANCH
git reset --hard origin/$TARGET_BRANCH
git pull
CHECKOUT_BRANCH="feature/${TARGET_BRANCH}-${COMPONENT_NAME}-${COMPONENT_VERSION}"
echo "Creating feature branch: $CHECKOUT_BRANCH"
git checkout -b $CHECKOUT_BRANCH
sed -i "/.*version.*/c\ version: $COMPONENT_VERSION" files/$COMPONENT_NAME.yaml
git add files/$COMPONENT_NAME.yaml
## list file changes
git status
git -c user.name="unibot" -c user.email="unibot@il.example.com" commit -m "Update ${COMPONENT_NAME} to ${COMPONENT_VERSION}"
git push --set-upstream origin $CHECKOUT_BRANCH
'''
}
}
在这里,如果我没有权限去安装sshagent
plugin, 还有一个比较好的办法是,设置一个 dedicated node with pre-set SSH credential. 然后需要执行git check in任务的时候指定在这个node上进行即可。