0

I have a jenkins job foo that works perfectly well. It is authenticated with jenkins_foo_user. It is able to clone the repo and checkout the right branch.

In my codebase, I have another script - query_github.py a script used to query Github API to get information such as commits and pull request. To be able to use this API I need an access token.

I want to be able to use the jenkins user access token to authenticate and access the github credentials. How do I do this? Note: Using the Github Enterprise version

suprita shankar
  • 1,554
  • 2
  • 16
  • 47

3 Answers3

3

If you're using the Branch Source Plugin with GitHub App authentication, you don't have a token at hand in Jenkins. But the credentials provider is smart enough to give you an access token derived from the App with just the same withCredentials step:

withCredentials([usernamePassword(credentialsId: 'id-of-your-github-app-credentials',
                                  usernameVariable: 'GITHUB_APP',
                                  passwordVariable: 'GITHUB_ACCESS_TOKEN')]) {
  // Use the access token via $GITHUB_ACCESS_TOKEN here
}

Note that you have to use usernamePassword as type, even if your credentials referenced by ID are of type GitHub App.

See official Jenkins blog post n GitHub App authentication for further info.

biolauri
  • 535
  • 7
  • 18
0

You can define a password parameter in jenkins job and the same can be used in your github script.

Ex : You can define a password variable either as a build param or a new password variable using inject global passwords ( provide u have this plugin)

The same password can be used in script which use api

Below command uses github api call and will list down repos in your organization

Make sure <your_organization_name_HERE> is replaced with your organization name

curl --silent -q  -H "Authorization: token ${github_api_pwd}" https://api.github.com/orgs/<your_organization_name_HERE>/repos

Similarly you can get other information using other api's

prudviraj
  • 3,634
  • 2
  • 16
  • 22
0

one has to use the credentials api. Example

withCredentials([[$class: 'UsernamePasswordMultiBinding',
    credentialsId: 'jenkins-user',
    usernameVariable: 'Foo_USERNAME',
    passwordVariable: 'Foo_PASSWORD']]) {
      export foo_name=${stds.escape4sh env.Foo_USERNAME}
      export foo_pass=${stds.escape4sh env.Foo_PASSWORD}
      python foo.py

Inside of foo.py

_name = os.env.get('foo_name')
_pass = os.env.get('foo_pas')

easiest and cleanest way to accomplish the goal! Note: jenkins-user should be configured into jenkins user credentials

suprita shankar
  • 1,554
  • 2
  • 16
  • 47