Search code examples
jenkinssbtartifactory

Setting the value of a variable from build.sbt in the Jenkins job


I am new to Jenkins and Sbt, I am trying to to set the value of a variable in jenkins declared in build.sbt. To explain, i am trying to pusblish jars in artifactory repositories. I have two repositories one for releases and the other for Snapshots. in build.sbt :

publishTo := Some("Artifactory Realm" at "https://artifactory.mycloud.something.com/artifactory/sbt-handlereleases")
credentials += Credentials(Path.userHome / ".sbt" / ".credentials")
resolvers += "Artifactory" at "https://artifactory.mycloud.something.com/artifactory/sbt-handlereleases/"

in Jenkins job (build > execute shell) :

sbt clean compile package publish

this code enables me to publish jars in the releases repository in artifactory. however, if i want to publish in the snapshots repository, i will have to modify build.sbt with the right url for the snapshot repository (https://artifactory.mycloud.something.com/artifactory/sbt-handlesnapshots).

how can i set a variable in build.sbt ($URL_REPO) and specify it's value in the jenkins job by assigning the url for snapshots or releases? Any help is greatly appreciated. Thanks


Solution

  • To define the repository, you should use the publishTo setting. Here is an example from the Publishing docs:

    // in build.sbt
    publishTo := {
      val nexus = "https://my.artifact.repo.net/"
      if (isSnapshot.value)
        Some("snapshots" at nexus + "content/repositories/snapshots")
      else
        Some("releases"  at nexus + "service/local/staging/deploy/maven2")
    }
    

    This switch between the snapshots and releases repositories is based on the isSnapshot setting which usually just checks if the version setting has -SNAPSHOT suffix.

    If this works for your use case, this is the way to go. If it doesn't and you need to switch it depending on some external factor (e.g. how you trigger your Jenkins pipeline), you can introduce an environment variable in Jenkins and check it in publishTo definition:

    // in build.sbt
    publishTo := {
      if (sys.env.get("IS_SNAPSHOT").isDefined)
        Some("snapshots" at "...")
      else
        Some("releases"  at "...")
    }
    

    Or if you want to set the URL dynamically:

    publishTo := sys.env.get("URL_REPO").map{ url =>
      "publishing repository" at url
    }