Passing LDAP Credentials to httpRequest Step in Jenkins - jenkins

I what to make a httpRequest via pipeline with LDAP Credentials of pipeline triggering user.
LDAP Credentials need to be passed as 'authentication' property in httpRequest Step in pipeline.
pipeline {
agent any
stages{
stage('Remote Call'){
httpRequest url : <RemoteUrl> , authentication : 'LDAP_Credentails'
}
}
}
Suppose user with LDAP Credentials, say
LdapUsername : deerajk
LdapPasssword : dummyPassword
Note :Above mentioned Credentails are not not part of Jenkins Credential Store
Logs in to Jenkins with above mentioned Credentials and triggers a pipeline job , Say pipeline name 'MakeHttpRequestPipeline'. Mentioned pipeline makes an httpRequest call to which needs to use above mentioned Credentials in authentication property of httpRequest Step. This httpRequest is used to get token of LDAP user from Remote Jenkins and Trigger a job on Remote Jenkins.
What did i try ?
I could get user name how Triggered Job by following Code
def job = Jenkins.getInstance().getItemByFullName(env.JOB_BASE_NAME, Job.class)
def build = job.getBuildByNumber(env.BUILD_ID as int)
def userId = build.getCause(Cause.UserIdCause).getUserId()
I want to do the following
- Get LDAP Credentials reference id of user how triggers pipeline
- Pass the LDAP Credentials reference id in httpRequest Made by Pipeline
Let me know if their is a way to do so.

Get user Credentials via following parameters :
parameters{
credentials(credentialType: 'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl',
defaultValue: '', description: 'Select your LDAP from Drop Down if avaliable else Create it',
name: 'deployCredentialsId', required: true)
}
Use Credentials as follows :
stages{
stage('TRIGGER PIPELINE'){
steps{
withCredentials([usernameColonPassword( credentialsId: '${deployCredentialsId}' , variable: 'DEPLOY_KEY')]){
script{
def creds = "$DEPLOY_KEY"
String auth = creds.bytes.encodeBase64().toString()
def response = httpRequest customHeaders: [ [maskValue: false, name: 'Authorization', value: "Basic ${auth}"], [maskValue: false, name: 'Content-Type', value: 'application/json'],] ,
url : 'https://{jenkinsHost}/me/configure' , ignoreSslErrors: true
}
}
}
}
}
Sending Custom Headers works

Related

Jenkins Pipeline dynamically set parameter based on Artifactory trigger URL

I have a pipeline job that triggers when finding changes in Artifactory at a specific path. I want to pass the Artifactory url value to a parameter (my goal for this job is to allow users to manually build this job and enter a path as well as have this job automatically trigger when changes are found in a specific path in Artifactory and pass that value to the parameter).
node {
def server
def rtTriggerUrl = currentBuild.getBuildCauses('org.jfrog.hudson.trigger.ArtifactoryCause')[0]?.url
stage ('Artifactory configuration') {
server = Artifactory.server 'artifactory-1'
}
stage('Trigger build') {
server.setBuildTrigger spec: "H/2 * * * *", paths: "maven-examplerepo-local/path/to/jar"
}
}
pipeline {
parameters {
string(
name: 'JAR_LOCATION',
defaultValue: rtTriggerUrl,
trim: true,
description: 'Artifactory URL of jar'
I have tried setting it a couple different ways:
defaultValue: rtTriggerUrl
defaultValue: "${currentBuild.getBuildCauses('org.jfrog.hudson.trigger.ArtifactoryCause')[0]?.url}"
However these gave blank or null values (I also tried setting the rtTriggerUrl function before node to see if that'd make it available to the parameter but that didn't work either).
Has anyone figured out how to do this? As a workaround I created an upstream job that triggers when changes are in Artifactory, then it triggers the downstream job and passes the url value to the downstream job's parameter. I wanted to see if I could combine that logic into one job.

How to set Jenkins auth2 credential from String?

I'm using the Jenkins parametrised remote trigger plugin to call Jenkins server (A) from our Jenkins server (B). It's been working successfully using the Jenkins credential manager, but I'm now wishing to fetch it at run time and then pass in that fetched credential directly as a string, rather than have it stored in Jenkins.
Essentially I'm trying to get a String into an auth2 object to use in my remote trigger.
Existing code:
triggerRemoteJob job: "${REMOTE_JOB}",
parameters: "REDACTED",
auth: CredentialsAuth(credentials: "cred-id")
What I'm working towards:
def fetchedCred = getFromThirdPartyResource()
triggerRemoteJob job: "${REMOTE_JOB}",
parameters: "REDACTED",
auth: CredFromString(fetchedCred)
The solution really depends on the type of Authentication method you intend to use. Since you are using CredentialsAuth I assume you plan on using Basic Auth. In Basic Auth you will be passing the Authorization header like below
Authorization: Basic username:password (username:password will be base64 encoded)
So in order to get around your issue, you can use TokenAuth instead of CredentialsAuth. If you look at the code here TokenAuth is also generating a Basic Auth header with the provided apiToken and userName. Hence you can use something like the below.
pipeline {
agent any
stages {
stage('Test') {
steps {
script {
def password = new hudson.util.Secret('admin')
def username = 'admin'
triggerRemoteJob job: "http://localhost:8080/job/test", auth: TokenAuth(apiToken: password, userName: username)
}
}
}
}
}

GitHub Webhook not triggering the Jenkins Pipeline

I want to trigger a pipeline when Pull Request is Merged..ie "action": "closed","merged":"true"
Webhook got 200 response for Jenkins
pipeline.groovy:
pipelineJob(job_name) {
parameters {
stringParam('APP_URL', app_url, 'URL of the Application')
stringParam('APP_MERGE_STATUS', app_merge_status, 'Merge Status to Trigger Job')
booleanParam('MERGED', true, 'Flag to Trigger the job')
stringParam('APP_ARTIFACT_BUCKET', artifact_bucket, 'Bucket url to upload artifacts')
stringParam('payload')
}
triggers {
genericTrigger {
genericVariables {
genericVariable {
key("APP_MERGE_STATUS")
value("\$.action")
expressionType("JSONPath")
}
genericVariable {
key("MERGED")
value("\$pull_request.merged")
expressionType("JSONPath")
}
}
printPostContent(true)
regexpFilterText("\$action")
regexpFilterExpression("")
}
}
Generic Variables I have mentioned are also used to trigger the job without github..[using parameters]
I am not sure how to write the generic trigger variables and regex for the trigger
Scenario: PR is closed and merged
If your Jenkins is exposed to the internet, you can subscribe to the webhook in Github itself
or use jenkins declarative pipeline to make use of
Got the solution..I missed to add "generic-webhook-trigger" in payload url

Can I access current stage id in Jenkins pipeline?

I'm using shared library to build CI/CD pipelines in Jenkins. And in my case, some of the stages need to send the execute info through web apis. In this case, we need to add stage id for current stage to api calls.
How can I access the stage id similar with ${STAGE_NAME}?
I use Pipeline REST API Plugin as well as HTTP Request Plugin
Your methods in Jenkinsfile can look like:
#NonCPS
def getJsonObjects(String data){
return new groovy.json.JsonSlurperClassic().parseText(data)
}
def getStageFlowLogUrl(){
def buildDescriptionResponse = httpRequest httpMode: 'GET', url: "${env.BUILD_URL}wfapi/describe", authentication: 'mtuktarov-creds'
def buildDescriptionJson = getJsonObjects(buildDescriptionResponse.content)
def stageDescriptionId = false
buildDescriptionJson.stages.each{ it ->
if (it.name == env.STAGE_NAME){
stageDescriptionId = stageDescription.id
}
}
return stageDescriptionId
}
Questiion is old but i found the solution: use some code from pipeline-stage-view-plugin( looks like it is already installed in jenkins by default)
we can take current job ( workflowrun ) and pass it as an argument to
com.cloudbees.workflow.rest.external.RunExt.create , and whoala: we have object that contains info about steps and time spent on it's execution.
Full code will looks like this:
import com.cloudbees.workflow.rest.external.RunExt
import com.cloudbees.workflow.rest.external.StageNodeExt
def getCurrentBuildStagesDuration(){
LinkedHashMap stagesInfo = [:]
def buildObject = com.cloudbees.workflow.rest.external.RunExt.create(currentBuild.getRawBuild())
for (StageNodeExt stage : buildObject.getStages()) {
stagesInfo.put(stage.getName(), stage.getDurationMillis())
}
return stagesInfo
}
Function will return
{SomeStage1=7, SomeStage2=1243, SomeStage3=5}
Tested with jenkins shared library and Jenkins 2.303.1
Hope it helps someone )

Jenkins Pipeline passing password parameter to downstream job

I want to pass a value, from the Password Parameter plugin, in a Jenkins Pipeline job, to another freestyle job, to be used for login. I don't want to see it in the output or anywhere else. I can do it between two freestyle jobs but it seems that the pipeline is a bit different.
Even if I'm able to send as a string, it would be visible in the Parameters tab or the Environment Variables tab.
Does anyone have any idea how this could be achieved?
I've spent hours trying different solutions for the same problem as you've had and here is the final solution, which worked for me:
In your pipeline script:
stages {
stage("Do something with credentials and pass them to the downstream job") {
steps {
build job: 'your/jobname/path', parameters: [
[$class: 'hudson.model.PasswordParameterValue', name: 'PASSWORD', value: env.PASSWORD],
[$class: 'TextParameterValue', name: 'USERNAME', value: env.USERNAME]
]
}
}
The trick is to use hudson.model.PasswordParameterValue class when passing password parameter to downstream (Freestyle) job, but you must use then the same class for parameter definition in your main pipeline (parent job) in order to make it work.
For example in your pipeline job you would configure password parameter:
configure {
it / 'properties' / 'hudson.model.ParametersDefinitionProperty' / 'parameterDefinitions' << 'hudson.model.PasswordParameterDefinition' {
name('PASSWORD')
description('My password')
}
}
You should make sure that parent and child job both are using password parameters. Then, this parameters tab will mask you password. Making build parameters as password parameter will not mask passwords in environment variables tab, for that you need to enable mask password in child and parent job configuration or use Inject passwords to the build as environment variables and enable mask password.
You should use credentials plugin, which in pipeline you write with withCredentials block. For example:
withCredentials([usernamePassword(credentialsId: 'abcd1234-56ef-494f-a4d9-d5b5e8ac357d',
usernameVariable: 'USERNAME',
passwordVariable: 'PASSWORD')])
{
echo 'username='+USERNAME
echo 'password='+PASSWORD
}
where abcd1234-56ef-494f-a4d9-d5b5e8ac357d is the id of credentials you have in jenkins, and of course, as long as you don't echo the variables (as I did in the example obviously for demonstration purposes), username and password are not visible.
You can trigger you downstream job with the help of below plugin
Parameterized+Trigger+Plugin

Resources