Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

git - How do I get the SCM URL inside a Jenkins Pipeline or Multibranch Pipeline?

I am trying to get a prebuild merge to work inside a multibranch pipeline and I would like to avoid having to hardcode the git url in my pipeline script.

It seems like scm step must store the url somehow, but I cannot figure out how to access it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are correct, the scm object does have the information you need.

When using git as the source control in a Pipeline project (or Multibranch Pipeline project), the scm global variable will be an instance of GitSCM. That means that `scm.getUserRemoteConfigs()' will return a list of UserRemoteConfig instances. Those instances have the git remote's name, url, and refspec. You can iterate over that list to find a matching remote, or just take the first one if your sure you only have one url.

def scmUrl = scm.getUserRemoteConfigs()[0].getUrl()

NOTES

  • RejectedAccessException - The getUserRemoteConfigs and getUrl methods will both throw org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException until you manually approve them, under "Manage Jenkins -> In-process Script Approval". The only way I've found to do this is to try running the script, have it throw an access exception, approve the one method that caused the exception, and repeat for each method until no more access exceptions are thrown. Happily the setting is server-wide, so you only have to do this once per jenkins controller, not for each pipeline job.

  • GitHub - While testing with a GitHub-sourced multibranch pipeline, getUserRemoteConfigs returned two UserRemoteConfig instances, one for regular branches and another for pull requests. These had the same url so no big deal, but something to keep in mind. For example, in a project using an HTTPS-based connection:

    echo scm.getUserRemoteConfigs()
    
    "[
        +refs/heads/*:refs/remotes/origin/* => https://github.com/bitwiseman/project.git (origin),
        +refs/pull/*/head:refs/remotes/origin/pr/* => https://github.com/bitwiseman/project.git (origin)
    ]"
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...