Jenkinsfile example to publish into Artifactory

Here is a Jenkinsfile to upload and download artifacts from the Jfrog Artifactory. I really like to share this post as it took me few hours to get this working as I couldn’t find proper example on the internet.

You can install standalone Jfrog Artifactory in an EC2 Linux VM.

Next you will need to have the Artifactory plugin installed in the Jenkins. Go to Manage Jenkins->Configure System –> In server_id field mention name as Artifac_dev_server1 and provide the artifactory url, username and password.

Screenshot from 2018-09-20 11-15-24

You can fork and use the sample application source code from my github repo – https://github.com/raghuck/ant-Build-Project

Below is the Jenkinsfile file in groovy language syntax.

pipeline {
    agent any
    environment {
    def uploadSpec = """{
     "files": [
      {
          "pattern": "classes/abc/*",
          "target": "generic-local/"
        }
     ]
    }"""
    def downloadSpec = """{
     "files": [
      {
          "pattern": "generic-local/*",
          "target": "/home/ec2-user/.jenkins/workspace/testpipeline-1/downloads/"
        }
     ]
    }"""
    }
    
    stages {
        stage('Build') {
            steps {
                echo 'Building..'
                sh 'ant -f build.xml run'
            }
        }
        stage('Test') {
            steps {
                echo 'Publish the artifacts..'
                sh 'mkdir -p downloads'
                    script
                        {
                        //def server = Artifactory.newServer('http://10.213.243.17:8081/artifactory', 'admin', 'art@123')
                        def server = Artifactory.server 'Artifac_dev_server1'
                        server.bypassProxy = true
                        server.upload(uploadSpec)
                        echo 'Uploaded the file to Jfrog Artifactory successfully'
                        server.download(downloadSpec)
                        echo 'Downloaded the file from Jfrog Artifactory successfully'
                        }
            }
        }
        stage('Notify') {
            steps {
                echo 'Mail Notification...'
                mail body: 'Project build successful for job named testpipeline-1',
                from: 'test1@gmail.com',
                subject: 'project build successful',
                to: 'test2@gmail.com'
            }
        }
    }
}

There are 2 functions defined as uploadSpec and downloadSpec which contains the path and details about files/artifacts which needs to uploaded and downloaded. In the stage ‘Test’ the connection to the Artifactory happens and file gets uploaded using server.upload(uploadSpec). Similarly we can excute the download function by using server.download(downloadSpec)

The ‘Notify’ stage contains simple syntax to send mail with message as success or failure state of the job.

Advertisements