Working with Gradle

Artifactory provides tight integration with Gradle. All that is needed is a simple modification of the build.gradle script file with a few configuration parameters.

Both the new and older publishing mechanisms of Gradle are supported; some of the steps to configure the Gradle Artifactory Plugin depend on the version being used, and these are detailed in the documentation pages.

The Gradle Artifactory Plugin can be used whether you are running builds using a CI server or running standalone builds. In either case, you should note the following points:

  1. CI Server IntegrationWhen running Gradle builds in the continuous integration server, it is recommended to use one of the Artifactory Plugins for Jenkins, TeamCity or Bamboo.

    You can use the build server UI to configure resolving and publishing artifacts through Artifactory to capture exhaustive build information.

  2. Standalone Integration

    The Gradle Artifactory plugin offers a simple DSL to perform the following steps in your Gradle build:

    1. Define the default dependency resolution from Artifactory.
    2. Define configurations that publish artifacts to Artifactory after a full (multi-module) successful build.
    3. Define properties that should be attached to published artifacts in Artifactory metadata.
    4. Capture and publish a build-info object to the Artifactory build-info REST API to provide a fully traceable build context.
📘

Source Code Available.

This Gradle Artifactory Plugin is an open source project on GitHub which you can freely browse and fork.

Integration Benefits JFrog Artifactory and Gradle Repositories

Set up a Private, Remote and Virtual Maven/Gradle Registry

Configure Artifact Resolution

This section reviews how to Configure Artifact Resolution with Gradle

Use the Gradle Build Script Generator

With Artifactory's Gradle Build Script Generator, you can easily create a Gradle init script that handles resolution.

In the Artifact Repository Browser of the Artifacts module, select Set Me Up. In the Set Me Up dialog box, set Gradle in the Tool field and click "Generate Gradle Settings". You can now specify the settings you want to configure for Gradle.

SettingDescription
Plugin/Libs ResolverThe repository that should be used to resolve plugins/libraries
Use Maven/Use IvyWhen checked, specifies that resolving should be done using the Maven/Ivy pattern
Libs PublisherThe repository that should be used to publish libraries
Use Maven/Use IvyWhen checked, specifies that library should be published using a Maven/Ivy descriptor
Repository LayoutSpecifies the layout of the corresponding repository

After you have configured the settings for Gradle, you can click "Generate Settings" to generate and save the build.gradle and gradle.properties file.

Provision Dynamic Settings

Artifactory provides the ability to deploy and provision a dynamic settings template for your users. After being downloaded, settings are generated according to your own logic and can automatically include user authentication information.

For more information, see Provisioning Build Tool Settings under Filtered Resources.

Sample Build Script and Properties

You can download sample scripts from the JFrog GitHub public repository.

Running Gradle

To build your project and upload generated artifacts to Artifactory, run the following command:

gradle artifactoryPublish

For more information on building your projects with Gradle, see the Gradle Documentation.

Get Debug Information from Gradle

Run Gradle with the -d option to get useful and readable information if your build fails.

Dependency Declaration Snippets

Artifactory provides dependency declaration code snippets that you can copy into the Gradle dependency declaration section of your build.gradle file.

In the Artifact Repository Browser of the Artifacts module, drill down in the repository tree and select a relevant artifact. Under the Dependency Declaration section, select Gradle to display the corresponding dependency declaration that you can copy into your build.gradle file.

Dependency-Declaration-Snippets-gradle.png

Optimizing Gradle Builds

From version 3.5, Gradle introduces a build cache feature that enables you to reuse outputs produced by other builds, instead of rebuilding them, and dramatically reduce build time. This feature supports not only your local filesystem cache, but also remote caches that can be shared across your organization.

📘

Note

The Gradle team has measured an average reduction of 25% in total build time, and even a reduction of 80% with some of their commits!

To optimize your Gradle builds:

  1. Configure Artifactory to be your Gradle build cache
  2. Configure Gradle to use the build cache in Artifactory

Configure Artifactory to Be Your Gradle Build Cache

Artifactory can be used as the Gradle build cache by simply creating a generic repositories in Artifactory.

For example, the following is a simple use case where the Continuous Integration server builds a project and stores the build cache in Artifactory for later use by the following builds. This will greatly improve the build time in your local developer environments.

Build_Cache_1.png

Configure Gradle to use Build Cache

Configure Gradle to use the build cache and point it to Artifactory.

gradle.properties

artifactory_user=admin
artifactory_password=password
artifactory_url=http://localhost:8081/artifactory
org.gradle.caching=true
gradle.cache.push=false

settings.gradle

Set the _gradle.cache.pus_h property to true, on the CI server, by overriding it using -Pgradle.cache.push=true.

include "shared", "api", "services:webservice"

ext.isPush = getProperty('gradle.cache.push')

buildCache {
  local {
    enabled = false
  }
  remote(HttpBuildCache) {
   url = "${artifactory_url}/gradle-cache-example/"
   credentials {
    username = "${artifactory_user}"
    password = "${artifactory_password}"
   }
   push = isPush
  }
}

Replicate Across Different Sites

You can also use Artifactory as a distributed cache that’s synchronized across both local and remote teams using push and pull repository replication, and improve both your local and remote build times.

Build_Cache.png

Gradle Artifactory Plugin

Version 6 is now available.

JFrog is announcing the release of Version 6 for the Gradle Artifactory Plugin. This major release marks a significant milestone, introducing support for Gradle version 9. The code and documentation for Version 6 of the plugin are available at https://github.com/jfrog/artifactory-gradle-plugin

Note:

  • For Gradle version 6.9 through 8 (inclusive), use version 5.
  • For Gradle 9, use version 6

Version 6 includes the following breaking changes:

  • The minimum Java version required is 17.
  • The minimum supported Gradle version has been increased to 8.

Gradle Artifactory Plugin Version 5

This major release marks a significant milestone by completely rewriting the plugin code from Groovy to Java. The primary goal of this rewrite was to address several fundamental issues that existed in the previous versions, while also enabling the incorporation of additional functionality that was proving to be extremely challenging with Version 4. The code and documentation for Version 5 of the plugin can now be found at https://github.com/jfrog/artifactory-gradle-plugin.

For more information, see the Version 5 documentation here.

Version 5 includes the following breaking changes:

  1. The minimum supported Gradle version has been increased to 6.9. Consequently, the legacy archive configurations are no longer supported.
  2. The 'parent' closure in the 'artifactory' convention is no longer compatible or supported.

Examples: Project examples which use the Gradle Artifactory Plugin are available here.

Gradle Artifactory Plugin Version 4

The Gradle Artifactory Plugin allows you to deploy your build artifacts and build information to Artifactory and also to resolve your build dependencies from Artifactory. The minimum supported Gradle version is 4.10.

Download and Install the Gradle Artifactory Plugin Version 4

Build script snippet for use in all Gradle versions

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.+"
  }
}
apply plugin: "com.jfrog.artifactory"

Build script snippet for use in Gradle 2.1 and above

// Replace <plugin version> with the version of the Gradle Artifactory Plugin.
plugins {
  id "com.jfrog.artifactory" version "<plugin version>"
}

Tip

Currently the "plugins" notation cannot be used for applying the plugin for sub projects, when used from the root build script

Integration BenefitsJFrog Artifactory and Gradle Repositories

Configure the Gradle Artifactory Plugin Version 4

This section reviews how to configure the Gradel Artifactory Plugin Version 4.

Examples: Project examples which use the Gradle Artifactory Plugin are available here.

Use the Artifactory Plugin DSL

The Gradle Artifactory plugin is configured using its own Convention DSL inside the build.gradle script of your root project.

The syntax of the Convention DSL is described below:

We highly recommend also using our examples as a reference when configuring the DSL in your build scripts.

Tip

Mandatory items within the relevant context are prefixed with '+'. All other items are optional.

Dependencies Resolution

repositories {
        mavenCentral()
        maven {
                +url "http://repo.myorg.com/artifactory/libs-releases" // The Artifactory (preferably virtual) repository to resolve from
                credentials {                           // Optional resolver credentials (leave out to use anonymous resolution)
                        username = "resolver" // Artifactory user name
                password = "resolverPaS*" // Password or API Key
                }
        }
 
        ivy {
                +url "http://localhost:8081/artifactory/ivy-releases"
                layout "pattern", {           // Optional section for configuring Ivy-style resolution.
                ivy "[organization]/[module]/[revision]/ivy.xml"
                artifact "[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
                m2compatible = true     // Convert any dots in an [organization] layout value to path separators, similar to Maven's groupId-to-path conversion. False if not specified.
        }
        }
}
📘

Note

Follow this documentation for different ways to configure your repositories.

Artifacts and BuildInfo Publication

artifactory {
  +contextUrl = 'http://repo.myorg.com/artifactory'   //The base Artifactory URL if not overridden by the publisher/resolver
  publish {
    contextUrl = 'http://repo.myorg.com/artifactory'   //The base Artifactory URL for the publisher
    //A closure defining publishing information
    repository {
      +repoKey = 'integration-libs'   //The Artifactory repository key to publish to
      +username = 'deployer'          //The publisher user name
      password = 'deployerPaS*'       //The publisher password or API key
      ivy {
        //Optional section for configuring Ivy publication. Assumes Maven repo layout if not specified
        ivyLayout = '[organization]/[module]/[revision]/[type]s/ivy-[revision].xml'
        artifactLayout = '[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]'
        mavenCompatible = true //Convert any dots in an [organization] layout value to path separators, similar to Maven's groupId-to-path conversion. True if not specified
      }
    }
    defaults {
                //List of Gradle Publications (names or objects) from which to collect the list of artifacts to be deployed to Artifactory.
        //If you'd like to deploy the artifacts from all the publications defined in the Gradle script, you can set the 'ALL_PUBLICATIONS' string, instead of the publication names.
        publications ('ivyJava','mavenJava','foo')
                //List of Gradle Configurations (names or objects) from which to collect the list of artifacts to be deployed to Artifactory. 
                publishConfigs('archives', 'published')                    
        properties = ['qa.level': 'basic', 'q.os': 'win32, deb, osx']  //Optional map of properties to attach to all published artifacts
        /*
        The properties closure in the "defaults" task uses the following syntax:
        properties {
            publicationName 'group:module:version:classifier@type', key1:'value1', key2:'value2', ...
        }
        publicationName: A valid name for a publication of the project. You can use all to apply the properties to all publications.
        group:module:version:classifier@type: A filter that specifies the artifacts to which properties should be attached. 
                The filter may contain wildcards: * for all characters or ? for a single character.
        key:'value': A list of key/value properties that will be attached to to the published artifacts matching the filter.  
        */
        properties {                                                   //Optional closure to attach properties to artifacts based on a list of artifact patterns per project publication
            foo '*:*:*:*@*', platform: 'linux', 'win64'                //The property platform=linux,win64 will be set on all artifacts in foo publication
            mavenJava 'org.jfrog:*:*:*@*', key1: 'val1'                //The property key1=val1 will be set on all artifacts part of the mavenJava publication and with group org.jfrog
            all 'org.jfrog:shared:1.?:*@*', key2: 'val2', key3: 'val3' //The properties key2 and key3 will be set on all published artifacts (all publications) with group:artifact:version 
                                                                                                                                           //equal to org.jfrog:shared:1.?
        }
        publishBuildInfo = true   //Publish build-info to Artifactory (true by default)
        publishArtifacts = true   //Publish artifacts to Artifactory (true by default)
        publishPom = true   //Publish generated POM files to Artifactory (true by default).
        publishIvy = true   //Publish generated Ivy descriptor files to Artifactory (true by default).
    }
  }
  // Redefine basic properties of the build info object
  clientConfig.setIncludeEnvVars(true)
  clientConfig.setEnvVarsExcludePatterns('*password*,*secret*')
  clientConfig.setEnvVarsIncludePatterns('*not-secret*')
  clientConfig.info.addEnvironmentProperty('test.adding.dynVar',new java.util.Date().toString())
  clientConfig.info.setBuildName('new-strange-name')
  clientConfig.info.setBuildNumber('' + new java.util.Random(System.currentTimeMillis()).nextInt(20000))
  clientConfig.info.setProject('project-key') 
  clientConfig.timeout = 600 // Artifactory connection timeout (in seconds). The default timeout is 300 seconds.
  clientConfig.setInsecureTls(false) // Set to true to skip TLS certificates verification (false by default).
}

Controlling how environment variables are exposed

As shown in the example above, you can control which environment variables are exposed in clientConfig.setIncludeEnvVars using clientConfig.setEnvVarsExcludePatterns and clientConfig.setEnvVarsIncludePatterns. These calls specify which environment variables should be excluded or included respectively using a parameter which is a comma-separated list of expressions to exclude or include. The expressions can use a star ('*') wildcard to specify multiple environment variables.

Using the old Gradle publishing mechanism? Expand source

If you are using the old Gradle publishing mechanism, you need to replace the above defaults closure with the following one:
 
defaults {
        //This closure defines defaults for all 'artifactoryPublish' tasks of all projects the plugin is applied to
        publishConfigs ('a','b','foo')                                 //Optional list of configurations (names or objects) to publish.
                                                                       //The 'archives' configuration is used if it exists and no configuration is specified
        mavenDescriptor = '/home/froggy/projects/proj-a/fly-1.0.pom'   //Optional alternative path for a POM to be published (can be relative to project baseDir)
        ivyDescriptor = 'fly-1.0-ivy.xml'                              //Optional alternative path for an ivy file to be published (can be relative to project baseDir)
        properties = ['qa.level': 'basic', 'q.os': 'win32, deb, osx']  //Optional map of properties to attach to all published artifacts
        /*
        The properties closure in the "defaults" task uses the following syntax:
        properties {
            configuration 'group:module:version:classifier@type', key1:'value1', key2:'value2', ...
        }
        configuration: A configuration that is a valid name of a configuration of the project. You can use all to apply the properties to all configurations.
        group:module:version:classifier@type: An artifact specification filter for matching the artifacts to which properties should be attached. 
                The filter may contain wildcards: * for all characters or ? for a single character.
        key:'value': A list of key/value(s) properties that are attached to to the published artifacts matching the filter.
        */
        properties {                                                   //Optional closure to attach properties to artifacts based on a list of artifact patterns per project configuration
            foo '*:*:*:*@*', platform: 'linux', 'win64'                //The property platform=linux,win64 will be set on all artifacts in foo configuration
            archives 'org.jfrog:*:*:*@*', key1: 'val1'                 //The property key1=val1 will be set on all artifacts part of the archives configuration and with group org.jfrog
            all 'org.jfrog:shared:1.?:*@*', key2: 'val2', key3: 'val3' //The properties key2 and key3 will be set on all published artifacts (all configurations) with group:artifact:version 
                                                                       //equal to org.jfrog:shared:1.?
        }
        publishBuildInfo = true   //Publish build-info to Artifactory (true by default)
        publishArtifacts = true   //Publish artifacts to Artifactory (true by default)
        publishPom = true         //Publish generated POM files to Artifactory (true by default)
        publishIvy = false        //Publish generated Ivy descriptor files to Artifactory (false by default)
    }
The Artifactory Project Publish Task

The Artifactory Publishing Plugin creates an artifactoryPublish Gradle task for each project the plugin is applied to. The task is configured by the publish closure of the plugin.

You can configure the project-level task directly with the task's artifactoryPublish closure, which uses identical Syntax to that of the plugin's publish.defaults closure.

artifactoryPublish {
    skip = false //Skip build info analysis and publishing (false by default)
        contextUrl = 'http://repo.myorg.com/artifactory'
    publications ('a','b','c')
    properties = ['qa.level': 'basic', 'q.os': 'win32, deb, osx']
    properties {
        c '**:**:**:*@*', cProperty: 'only in c'
    }
        clientConfig.publisher.repoKey = 'integration-libs'
        clientConfig.publisher.username = 'deployer'
        clientConfig.publisher.password = 'deployerPaS'

    clientConfig.publisher.setExcludePatterns("*artifacts-to-exclude-1*,*artifacts-to-exclude-2*") // Comma-separated list of excluded patterns. Artifacts matched to one of the patterns will not be deployed.
    clientConfig.publisher.setFilterExcludedArtifactsFromBuild(true) // Set to true to avoid adding the filtered artifacts to the build-info.

    // Minimum file size in KB for which the plugin performs checksum deploy optimization. Default: 10. Set to 0 to disable uploading files with checksum that already exists in Artifactory.
    clientConfig.publisher.minChecksumDeploySizeKb = 10
}
Control Publication in Sub-Projects with Gradle

The Gradle Artifactory Plugin allows you to define different publication configuration for sub projects. You may also define the configuration once for the whole project by defining the artifactory closure only in the root project. The plugin also lets you disable publication for a sub-module.

  • When defining the configuration anywhere in the hierarchy, all sub-projects beneath it inherit the configuration and can override it whether it is defined in the root or in a sub-project.

  • Each sub-project can override the publish closure or the repositories closure, or both of them.

    Example for overriding publication only

    artifactory {
            publish {
                    contextUrl = 'http://localhost:8081/artifactory'
                    repository {
                            repoKey = "libs-snapshot-local"
                            username = "user"
                            password = "pass"
                    }
            }
    }
  • For buildInfo to be published, a publish closure must be defined in the root project.

  • Use the artifactoryPublish.skip flag to deactivate analysis and publication.

  • Activate the corresponding artifactoryPublish Gradle task manually for each project to which you wish to apply the plugin. For example in our Gradle project examples you can run:

    Activating the plugin manually

    ./gradlew clean api:artifactoryPublish shared:artifactoryPublish
Control Build Name and Number with Gradle

By default, BuildInfo is published with a build name constructed from the name of your root project and a build number that is the start date of the build.

You can control the build name and number values by specifying the following properties respectively:

Specifying the build name and number

buildInfo.build.name=my-super-cool-build
buildInfo.build.number=r9001

The above properties should be added to your project's gradle.properties file.

Use HTTP proxy with the Gradle Artifactory Plugin Version 4

For deployment, add the following fields to the Artifactory closure in thebuild.gradle.

artifactory {
  ...
  clientConfig.proxy.host = 'www.somehost.org'
  clientConfig.proxy.port = '8080'
  clientConfig.proxy.username = 'userid'
  clientConfig.proxy.password = 'password'
}

The Artifactory Gradle plugin does not intervene in the Gradle dependency resolution process. Therefore to resolve the Gradle dependencies, use the regular Gradle proxy configuration configured in the gradle.properties file.

systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password