Programming

이름과 버전 쌍으로 설치된 Jenkins 플러그인 목록을 얻는 방법

procodes 2020. 6. 30. 21:38
반응형

이름과 버전 쌍으로 설치된 Jenkins 플러그인 목록을 얻는 방법


설치된 Jenkins 플러그인 목록을 얻으려면 어떻게해야합니까?

Jenkins Remote Access API 문서를 검색했지만 찾을 수 없습니다. Jenkins의 CLI를 사용해야합니까? 문서 나 예제가 있습니까?


를 방문하여 액세스 할 수 있는 Jenkins 스크립트 콘솔사용하여 정보를 검색 할 수 있습니다 http://<jenkins-url>/script. (로그인하고 필요한 권한을 가지고 있음).

스크립트 콘솔의 스크린 샷

다음 Groovy 스크립트입력하여 설치된 플러그인을 반복하고 관련 정보를 인쇄하십시오.

Jenkins.instance.pluginManager.plugins.each{
  plugin -> 
    println ("${plugin.getDisplayName()} (${plugin.getShortName()}): ${plugin.getVersion()}")
}

다음과 같이 결과 목록이 인쇄됩니다 (클리핑).

스크립트 출력 스크린 샷

이 솔루션은 Groovy를 사용한다는 점에서 위의 답변 중 하나 와 비슷 하지만 여기서는 스크립트 콘솔을 대신 사용합니다. 스크립트 콘솔은 Jenkins를 사용할 때 매우 유용합니다.

최신 정보

정렬 된 목록을 선호하는 경우이 sort메소드를 호출 할 수 있습니다 .

Jenkins.instance.pluginManager.plugins.sort { it.getDisplayName() }.each{
  plugin -> 
    println ("${plugin.getDisplayName()} (${plugin.getShortName()}): ${plugin.getVersion()}")
}

취향에 맞게 폐쇄를 조정하십시오.


요즘 나는 https://stackoverflow.com/a/35292719/1597808 대신 @Behe에 설명 된 답변과 동일한 접근법을 사용합니다.


깊이, XPath 및 랩퍼 인수와 함께 API를 사용할 수 있습니다.

다음은 설치된 모든 플러그인을 나열하기 위해 pluginManager의 API를 쿼리하지만 shortName 및 version 속성 만 리턴합니다. 물론 '|'를 추가하여 추가 필드를 검색 할 수 있습니다 XPath 매개 변수의 끝에 노드를 식별하기위한 패턴을 지정하십시오.

wget http://<jenkins>/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins

이 경우 래퍼 인수가 필요합니다. 여러 개의 필드가 XPath 및 여러 플러그인 노드와 일치한다는 점에서 결과의 일부로 둘 이상의 노드를 반환하기 때문입니다.

브라우저에서 다음 URL을 사용하여 사용 가능한 플러그인 정보를 확인한 다음 XPath를 사용하여 제한 할 항목을 결정하는 것이 좋습니다.

http://<jenkins>/pluginManager/api/xml?depth=1

젠킨스 1.588 (2 11 월 2014 년) 1.647 (4 월, 2016)

  • 젠킨스> 젠킨스 관리

    여기에 이미지 설명을 입력하십시오

  • 시스템 정보

    여기에 이미지 설명을 입력하십시오

  • 플러그인

    여기에 이미지 설명을 입력하십시오


다음과 같이 Jenkins CLI를 사용하십시오.

java -jar jenkins-cli.jar -s http://[jenkins_server] groovy = < pluginEnumerator.groovy

=호출에서 '표준 입력에서 읽기'를 의미 합니다. pluginEnumerator.groovy 는 다음 Groovy 코드를 포함합니다.

println "Running plugin enumerator"
println ""
def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
plugins.each {println "${it.getShortName()} - ${it.getVersion()}"}
println ""
println "Total number of plugins: ${plugins.size()}"

코드를 사용하려면 Jenkins Java API 문서가 있습니다.


Jenkins CLI는 설치된 모든 플러그인 나열을 지원합니다.

java -jar jenkins-cli.jar -s http://localhost:8080/ list-plugins


여기에 대한 답변은 다소 불완전했습니다. 그리고 실제로 플러그인 목록을 얻기 위해 다른 소스의 정보를 컴파일해야했습니다.

1. Jenkins CLI 받기

Jenkins CLI를 사용하면 명령 줄에서 Jenkins 서버와 상호 작용할 수 있습니다. 간단한 컬 호출로 얻을 수 있습니다.

curl 'localhost:8080/jnlpJars/jenkins-cli.jar' > jenkins-cli.jar

2. 파싱을위한 Groovy 스크립트 생성 (malenkiy_scot 덕분에)

다음을로 저장하십시오 plugins.groovy.

def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
plugins.each {println "${it.getShortName()}: ${it.getVersion()}"}

3. 플러그인 결과를 위해 Jenkins API 호출

Call the Jenkins server (localhost:8080 here) with your login username and password while referencing the Groovy script:

java -jar jenkins-cli.jar -s http://localhost:8080 groovy --username "admin" --password "admin" = < plugins.groovy > plugins.txt

The output to plugins.txt looks like this:

ace-editor: 1.1
ant: 1.5
antisamy-markup-formatter: 1.5
authentication-tokens: 1.3
blueocean-autofavorite: 1.0.0
blueocean-commons: 1.1.4
blueocean-config: 1.1.4
blueocean-dashboard: 1.1.4
blueocean-display-url: 2.0
blueocean-events: 1.1.4
blueocean-git-pipeline: 1.1.4
blueocean-github-pipeline: 1.1.4
blueocean-i18n: 1.1.4
blueocean-jwt: 1.1.4
blueocean-personalization: 1.1.4
blueocean-pipeline-api-impl: 1.1.4
blueocean-pipeline-editor: 0.2.0
blueocean-pipeline-scm-api: 1.1.4
blueocean-rest-impl: 1.1.4

If you're working in a docker environment and want to output the plugin list in a plugins.txt format in order to pass that to the install_scripts.sh use this script in the http://{jenkins}/script console

Jenkins.instance.pluginManager.plugins.each{
  plugin -> 
    println ("${plugin.getShortName()}:${plugin.getVersion()}")
}

Behe's answer with sorting plugins did not work on my Jenkins machine. I received the error java.lang.UnsupportedOperationException due to trying to sort an immutable collection i.e. Jenkins.instance.pluginManager.plugins. Simple fix for the code:

List<String> jenkinsPlugins = new ArrayList<String>(Jenkins.instance.pluginManager.plugins);
jenkinsPlugins.sort { it.displayName }
              .each { plugin ->
                   println ("${plugin.shortName}:${plugin.version}")
              }

Use the http://<jenkins-url>/script URL to run the code.


If you are a Jenkins administrator you can use the Jenkins system information page:

http://<jenkinsurl>/systemInfo

From the Jenkins home page:

  1. Click Manage Jenkins.
  2. Click Manage Plugins.
  3. Click on the Installed tab.

Or

  1. Go to the Jenkins URL directly: {Your Jenkins base URL}/pluginManager/installed

Sharing another option found here with credentials

JENKINS_HOST=username:password@myhost.com:port
curl -sSL "http://$JENKINS_HOST/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins" | perl -pe 's/.*?<shortName>([\w-]+).*?<version>([^<]+)()(<\/\w+>)+/\1 \2\n/g'|sed 's/ /:/'

With curl and jq:

curl -s <jenkins_url>/pluginManager/api/json?depth=1 \
  | jq -r '.plugins[] | "\(.shortName):\(.version)"' \
  | sort

This command gives output in a format used by special Jenkins plugins.txt file which enables you to pre-install dependencies (e.g. in a docker image):

ace-editor:1.1
ant:1.8
apache-httpcomponents-client-4-api:4.5.5-3.0

Example of a plugins.txt: https://github.com/hoto/jenkinsfile-examples/blob/master/source/jenkins/usr/share/jenkins/plugins.txt


I think these are not good enough answer(s)... many involve a couple of extra under-the-hood steps. Here's how I did it.

sudo apt-get install jq

...because the JSON output needs to be consumed after you call the API.

#!/bin/bash
server_addr = 'jenkins'
server_port = '8080'

curl -s -k "http://${server_addr}:${server_port}/pluginManager/api/json?depth=1" \
  | jq '.plugins[]|{shortName, version,longName,url}' -c | sort \
  > plugin-list

echo "dude, here's your list: "
cat plugin-list

I wanted a solution that could run on master without any auth requirements and didn't see it here. I made a quick bash script that will pull out all the versions from the plugins dir.

if [ -f $JENKINS_HOME/plugin_versions.txt ]; then
  rm $JENKINS_HOME/plugin_versions.txt
fi

for dir in $JENKINS_HOME/plugins/*/; do
  dir=${dir%*/}
  dir=${dir##*/}
  version=$(grep Plugin-Version $JENKINS_HOME/plugins/$dir/META-INF/MANIFEST.MF | awk -F': ' '{print $2}')
  echo $dir $version >> $JENKINS_HOME/plugin_versions.txt
done

Another option for Python users:

from jenkinsapi.jenkins import Jenkins

#get the server instance
jenkins_url = 'http://<jenkins-hostname>:<jenkins-port>/jenkins'
server = Jenkins(jenkins_url, username = '<user>', password = '<password>')

#get the installed plugins as list and print the pairs
plugins_dictionary = server.get_plugins().get_plugins_dict()
for key, value in plugins_dictionary.iteritems():
    print "Plugin name: %s, version: %s" %(key, value.version)

There is a table listing all the plugins installed and whether or not they are enabled at http://jenkins/systemInfo


If Jenkins run in a the Jenkins Docker container you can use this command line in Bash:

java -jar /var/jenkins_home/war/WEB-INF/jenkins-cli.jar -s http://localhost:8080/ list-plugins --username admin --password `/bin/cat /var/jenkins_home/secrets/initialAdminPassword`

For Jenkins version 2.125 the following worked.

NOTE: Replace sections that say USERNAME and APIKEY with a valid UserName and APIKey for that corresponding user. The API key for a user is available via Manage UsersSelect UserAPI Key option.

You may have to extend the sleep if your Jenkins installation takes longer to start.

The initiation yum update -y will upgrade the version as well if you installed Jenkins using yum as well.

#JENKINS AUTO UPDATE SCRIPT link this script into a cron
##############
!/bin/bash
sudo yum update -y
sleep 120
UPDATE_LIST=$( sudo /usr/bin/java -jar /var/cache/jenkins/war/WEB-INF/jenkins-cli.jar -auth [USERNAME:APIKEY] -s http://localhost:8080/ list-plugins | grep -e ')$' | awk '{ print $1 }' );
if [ ! -z "${UPDATE_LIST}" ]; then
    echo Updating Jenkins Plugins: ${UPDATE_LIST};
    sudo /usr/bin/java -jar /var/cache/jenkins/war/WEB-INF/jenkins-cli.jar -auth [USERNAME:APIKEY] -s http://localhost:8080/ install-plugin ${UPDATE_LIST};
    sudo /usr/bin/java -jar /var/cache/jenkins/war/WEB-INF/jenkins-cli.jar -auth [USERNAME:APIKEY] -s http://localhost:8080/ safe-restart;
fi
##############

There are lots of way to fetch this information but I am writing two ways as below : -

1. Get the jenkins cli.

The jenkins CLI will allow us to interact with our jenkins server from the command line. We can get it with a simple curl call.

curl 'localhost:8080/jnlpJars/jenkins-cli.jar' > jenkins-cli.jar

2. Create a groovy script. OR from jenkins script console

We need to create a groovy script to parse the information we receive from the jenkins API. This will output each plugin with its version. Save the following as plugins.groovy.

def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins() plugins.each {println "${it.getShortName()}: ${it.getVersion()}"}


You can be also interested what updates are available for plugins. For that, you have to merge the data about installed plugins with information about updates available here https://updates.jenkins.io/current/update-center.json .

다운로드 한 파일을 JSON으로 구문 분석하려면 두 번째 행 (온라인)을 온라인으로 읽어야합니다.


# list of plugins in sorted order
# Copy this into your Jenkins script console
    def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()

    List<String> list = new ArrayList<String>()

    i = 0
    plugins.each {
      ++i
      //println " ${i}  ${it.getShortName()}: ${it.getVersion()}"
      list.add("${it.getShortName()}: ${it.getVersion()}")
    }

    list.sort{it}
    i = 0
    for (String item : list) {
      i++
      println(" ${i} ${item}")
    }

참고 : https://stackoverflow.com/questions/9815273/how-to-get-a-list-of-installed-jenkins-plugins-with-name-and-version-pair

반응형