jenkins job DSL from remote SCM

61 Views Asked by At

I created a job DSL script for my projects to run on jenkins, the job cotains tokens and secrets. Hence, i used a bitbucket as my remote SCM. and stored the tokens as secrets. the question is how to make jenkins get the values of secrets when i run it via jenkins, or if there's a method to run directly via bitbucket pipelines ?

another method is to store the secrets in jenkins as credentials and retreive them during execution. but idk really how to do so the steps is as follows:

def x = {"service": "servicetoken", "service":"servicetoken"}

for service,token in x: do x do y

i tried to add them as plain text in the first release of my job DSL (before i include it in SCM) and worked but the secret is in the method of how to do this in a secure way

1

There are 1 best solutions below

1
Matthias On BEST ANSWER

If you want to use credentials within a pipeline you can use the credentials binding (https://www.jenkins.io/doc/pipeline/steps/credentials-binding/):

withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) { ... }

If you then want to use it in your JobDSL, make sure to specify your JobDSL code within GStrings ("-double quotes).

"""
job('example') {
  steps {
    batchFile(echo $USERPASS >secret.txt)
  }
}
"""

In case you are trying to resolve those variables within aJobDSL script file, rather than hard coded into your pipeline, you could do something like this:

def dslScripts = findFiles(glob: 'job-dsl/*.groovy')
dslScripts.each {
    def scriptContent = readFile(it.path)
    def interpolatedScript = evaluate("return \"\"\"${scriptContent}\"\"\"")
    
    jobDsl scriptText: interpolatedScript, sandbox: true
}