How to Pass Artifactory Credential to Gradle Build in a Jenkins pipeline Script?
July 3, 2023 2023-08-07 6:33How to Pass Artifactory Credential to Gradle Build in a Jenkins pipeline Script?
To pass Artifactory credentials to Gradle in a Jenkins Pipeline job, you can use the Jenkins Artifactory Plugin and the Jenkins Credentials Plugin. The Artifactory plugin integrates Artifactory repositories with Jenkins, allowing you to resolve and deploy artifacts during your build process.
Set up Artifactory credentials
- Navigate to “Jenkins” > “Manage Jenkins” > “Manage Credentials.
- “Click on “Jenkins” (or “Global”) and then “Add Credentials.”
- Choose the “Username with password” option.
- Enter your Artifactory username and password.
- Optionally, you can set an ID for these credentials (e.g., “artifact-creds”) to use it later in the pipeline script.
Create a Jenkins Pipeline job
- Go to the Jenkins dashboard and click on “New Item”.
- Enter a name for your pipeline job and select “Pipeline” as the job type.
- Scroll down and find the “Pipeline” section.
pipeline {
agent any
environment {
// You can set the environment variables here if it's required
}
stages {
stage('Checkout-Code') {
steps {
// This stage checks out your source code from version control (e.g., Git or SVN)
// Add your SCM checkout step here with branches or tags
}
}
stage('Build') {
steps {
// This stage executes the Gradle build using Artifactory credentials
// The credentials are passed as environment variables to the Gradle
script {
def artifactoryCreds = credentials('artifact_creds')
withCredentials([usernamePassword(credentialsId: artifactoryCreds, usernameVariable: 'ARTIFACTORY_USERNAME', passwordVariable: 'ARTIFACTORY_PASSWORD')]) {
// Next, Execute your Gradle build and passing the credentials as environment variables
sh './gradlew build -Partifactory_user=${env.ARTIFACTORY_USERNAME} -Partifactory_password=${env.ARTIFACTORY_PASSWORD}'
}
}
}
}
// Add more stages as needed for your pipeline builds
}
}
Explanation:
- In the environment block, you can set other environment variables needed for your build, if any.
- In the Build stage, we use the credentials function from Jenkins to access the Artifactory credentials previously configured in Jenkins.
- We then use the withCredentials block to mask the credentials during execution.
- Inside the withCredentials block, we execute the Gradle build using sh (Shell script), passing the Artifactory username and password as environment variables (USER_1 and PSWD_1, respectively) to Gradle.
- Replace ‘./gradlew build’ with your actual Gradle build command, and adjust the options and tasks as needed for your specific project.
This pipeline script will now run your Gradle build with the provided Artifactory credentials in a Jenkins Pipeline job.