Учетные данные Jenkins git работают в стадии, а не в следующей - PullRequest
1 голос
/ 17 мая 2019

У меня есть следующий файл конвейеров:

node('git') {
    stage('Set Git Config') {
        sh 'git config --global user.email "jenkins@test.com"'
        sh 'git config --global user.name "jenkins"'
        sh 'git config --global credential.helper cache'
        sh "git config --global credential.helper 'cache --timeout=3600'"
    }
    stage('Set Git Credentials') {
        git credentialsId: 'gitlab1', url: '${GITLAB1_REPO}'
        git credentialsId: 'gitlab2', url: '${GITLAB2_REPO}'
    }
    stage('Synchronize with Gitlab2'){
        sh 'git clone --bare ${GITLAB1_REPO} tfs'
        dir("tfs") {
            //add a remote repository
            sh 'git remote add --mirror=fetch second ${GITLAB2_REPO}'
            // update the local copy from the first repository
            sh 'git fetch origin --tags'

            // update the local copy with the second repository
            sh 'git fetch second --tags'

            // sync back the second repository
            sh 'git push second --all'
            sh 'git push second --tags'
        }
    }
}

Этап 1 и этап 2 работают отлично.Этап 3 завершается с ошибкой.

Я нахожу это странным, поскольку на этапе 2 я уже вижу, какой был последний коммит, поэтому он указывает, что учетные данные работают.Почему они не работают на этапе 3?

Это ошибка, которую я вижу:

git clone --bare git@bitbucket.test/test.git tfs Клонирование впустой репозиторий 'tfs' ... В доступе отказано (publickey).Неустранимый: Не удалось прочитать из удаленного репозитория.

На этапе 2 я вижу:

git config core.sparsecheckout # timeout = 10 git checkout -f 30f1a7d1b77ef64e1cd44eab11a6ef4541c23b43 ветвь git -a -v --no-abbrev # timeout = 10 ветвь git -D master # тайм-аут = 10 git checkout -b master 30f1a7d1b77ef64e1cd44eab11a6ef4541c23b43

10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 0

1 Ответ

2 голосов
/ 17 мая 2019

Стадия 1 - вы добавляете некоторые параметры оболочки в локальный git

Стадия 2 - вы указываете на фактические учетные данные, которые следует использовать, и используете плагин Jenkins - который будет просто работать

Satge 3- обратно в оболочку, учетные данные, предоставленные jenkins, не предоставляются, поэтому контекст является подчиненным / локальным пользователем jenkins.

Решением будет использование withCredentials для имени пользователя и пароля или sshagent(credentials...) для закрытого ключа

// credentialsId here is the credentials you have set up in Jenkins for pushing
// to that repository using username and password.
withCredentials([usernamePassword(credentialsId: 'git-pass-credentials-ID', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh("git tag -a some_tag -m 'Jenkins'")
    sh('git push https://${GIT_USERNAME}:${GIT_PASSWORD}@<REPO> --tags')
}

// For SSH private key authentication, try the sshagent step from the SSH Agent plugin.
sshagent (credentials: ['git-ssh-credentials-ID']) {
    sh("git tag -a some_tag -m 'Jenkins'")
    sh('git push <REPO> --tags')
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...