pythonbatch-fileenvironment-variablesjenkins-pluginscredential-manager

reading credentials from jenkins credential manager and integrating with python script


I have a python script which is making a couple of api calls and returning the response to me via email. I want to run this script through a jenkins pipeline job. I have a token, which I have stored in the jenkins credential manager as a secret text. The problem is that I am unsure as how to fetch this token in my python script. I have tried looking at a number of solutions, but all of those are leaving me confused. This is what my jenkins pipeline looks like:

pipeline {
    agent {
        node {
            label 'node1'
        }
    }
    environment {
        deva_stross_token=credentials('devadrita-stross') //i have saved the credential with id 'devadrita-stross', and this I understand, is fetching it for my pipeline
    }
    stages {
        stage('running python script') {
            steps {
                script {
                    bat """
                    python -u C://Users//Administrator//Desktop//stross//stross-script.py
                    """
                }
            }       
        }
    }
}

But what changes should I make to fetch it to my script? Here is the python script.

import requests
import urllib3
import json
import time
import os

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def initiateScan():
    url = ""

    payload={}
    files=[
    ('source',('amail.zip',open('C:/Users/Administrator/Desktop/stross/amail.zip','rb'),'application/zip')),
    ('metadata',('metadata.json',open('C:/Users/Administrator/Desktop/stross/metadata.json','rb'),'application/json'))
    ]
    headers = {
    'Authorization': ' Bearer **<token required here>**'
    }

    response = requests.request("POST", url, headers=headers, data=payload, files=files, verify=False)

    resp=response.json()
    print(resp)
    
    jobId=resp["job_id"]
    return(jobId)
    
def main():
   jobIdFromInitiate=initiateScan()

main()

Thank you in advance for your help!

EDIT- I understand that there are a few ways to do this, one with credentials() and one with environment variables. The problem is that I am mixing the two up and am not able to implement either method through code. So please help with code.

EDIT 1- Dividing @rok's answer into steps to follow- "(1)Add withCredentials block to your Jenkinsfile for reading the credentials and (2)binding them to environment variables. Then, (3)pass the values of the environment variables to your python script as arguments."

pipeline {
    agent {
        node {
            label 'node1'
        }
    }
    environment {
        deva_stross_token=credentials('devadrita-stross')
    }
    withCredentials([string(credentialsId: 'devadrita-stross', variable: 'deva-stross-token')]) {
    // some block
    }
    stages {
        stage('saving stross token and printing') {
            steps {
                script {
                    bat """
                    python -u C://Users//Administrator//Desktop//stross//stross-script.py
                    """
                }
            }       
        }
    }
}

(1) added withCredentials block for reading credentials (2) what is meant by binding the credentials with environment variables? Did the withCredentials block bind the token to environment variable 'deva-stross-token'? Is my environment block useful or needed here? (3) how to pass values of the environment variables to my python script?

I feel like I should add that I am relatively new to coding, so please bear with me if my questions seem very basic.


Solution

  • This is what worked for me: Jenkinsfile:

    stages {
            stage('run stross script') {
                steps{
                    withCredentials([string(credentialsId: 'devadrita-stross', variable: 'my_stross_token')]) {
                    echo "My stross token is '${my_stross_token}'!"
                    bat "python C:\\Users\\Administrator\\Desktop\\stross\\stross-script.py "
                    }
                }
            }
        }
    

    This binds my credential to the specified environment variable. I then import the variable to my python script, and use it like any other variable, i.e.- pass it to functions, etc. Here is a code snippet:

    def main():
        token = os.environ['my_stross_token']
        print(token)
        jobIdFromInitiate=initiateScan(token)
        getStatus(jobIdFromInitiate, token)