Извлечь значение из файла XML в конвейер Jenkinsfile, используя XmlParser (). ParseText (xml_file) - PullRequest
0 голосов
/ 08 января 2020

Следующая ситуация.

Цель: из конвейера Jenkins (Jenkinsfile из SCM) запустить другое задание сборки X. Но перед этим, для некоторых целей дальнейшей сложной конфигурации, я хочу проанализировать конфигурацию . xml этого задания сборки X и для извлечения его значения «remote», которое является путем к хранилищу задания сборки X.

Я создал правильно рабочий путь к конфигурации. xml задания по сборке X и теперь я могу сделать readFile для конфига. xml.

Вот как выглядит мой конфиг. xml:

<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description>Just a sample build job that should always be successful.</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.plugins.jira.JiraProjectProperty plugin="jira@3.0.11"/>
  </properties>
  <scm class="hudson.scm.SubversionSCM" plugin="subversion@2.12.2">
    <locations>
      <hudson.scm.SubversionSCM_-ModuleLocation>
        <remote>http://LAPTOP/svn/localrepo/CCC/COMPONENT/RC</remote>
        <credentialsId>someid</credentialsId>
        <local>.</local>
        <depthOption>infinity</depthOption>
        <ignoreExternalsOption>true</ignoreExternalsOption>
        <cancelProcessOnExternalsFail>true</cancelProcessOnExternalsFail>
      </hudson.scm.SubversionSCM_-ModuleLocation>
    </locations>
    <excludedRegions></excludedRegions>
    <includedRegions></includedRegions>
    <excludedUsers></excludedUsers>
    <excludedRevprop></excludedRevprop>
    <excludedCommitMessages></excludedCommitMessages>
    <workspaceUpdater class="hudson.scm.subversion.UpdateUpdater"/>
    <ignoreDirPropChanges>false</ignoreDirPropChanges>
    <filterChangelog>false</filterChangelog>
    <quietOperation>true</quietOperation>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders/>
  <publishers>
    <hudson.plugins.ws__cleanup.WsCleanup plugin="ws-cleanup@0.37">
      <patterns class="empty-list"/>
      <deleteDirs>false</deleteDirs>
      <skipWhenFailed>false</skipWhenFailed>
      <cleanWhenSuccess>true</cleanWhenSuccess>
      <cleanWhenUnstable>true</cleanWhenUnstable>
      <cleanWhenFailure>true</cleanWhenFailure>
      <cleanWhenNotBuilt>true</cleanWhenNotBuilt>
      <cleanWhenAborted>true</cleanWhenAborted>
      <notFailBuild>false</notFailBuild>
      <cleanupMatrixParent>false</cleanupMatrixParent>
      <externalDelete></externalDelete>
      <disableDeferredWipeout>false</disableDeferredWipeout>
    </hudson.plugins.ws__cleanup.WsCleanup>
  </publishers>
  <buildWrappers/>
</project>

Это вывод консоли конвейера Дженкинса для эха:

project[attributes={}; value=[description[attributes={}; value=[Just a sample build job that should always be successful.]], keepDependencies[attributes={}; value=[false]], properties[attributes={}; value=[hudson.plugins.jira.JiraProjectProperty[attributes={plugin=jira@3.0.11}; value=[]]]], scm[attributes={class=hudson.scm.SubversionSCM, plugin=subversion@2.12.2}; value=[locations[attributes={}; value=[hudson.scm.SubversionSCM_-ModuleLocation[attributes={}; value=[remote[attributes={}; value=[ http://LAPTOP/svn/localrepo/CCC/COMPONENT/RC]], credentialsId[attributes={}; value=[someid]], local[attributes={}; value=[.]], depthOption[attributes={}; value=[infinity]], ignoreExternalsOption[attributes={}; value=[true]], cancelProcessOnExternalsFail[attributes={}; value=[true]]]]]], excludedRegions[attributes={}; value=[]], includedRegions[attributes={}; value=[]], excludedUsers[attributes={}; value=[]], excludedRevprop[attributes={}; value=[]], excludedCommitMessages[attributes={}; value=[]], workspaceUpdater[attributes={class=hudson.scm.subversion.UpdateUpdater}; value=[]], ignoreDirPropChanges[attributes={}; value=[false]], filterChangelog[attributes={}; value=[false]], quietOperation[attributes={}; value=[true]]]], canRoam[attributes={}; value=[true]], disabled[attributes={}; value=[false]], blockBuildWhenDownstreamBuilding[attributes={}; value=[false]], blockBuildWhenUpstreamBuilding[attributes={}; value=[false]], triggers[attributes={}; value=[]], concurrentBuild[attributes={}; value=[false]], builders[attributes={}; value=[]], publishers[attributes={}; value=[hudson.plugins.ws__cleanup.WsCleanup[attributes={plugin=ws-cleanup@0.37}; value=[patterns[attributes={class=empty-list}; value=[]], deleteDirs[attributes={}; value=[false]], skipWhenFailed[attributes={}; value=[false]], cleanWhenSuccess[attributes={}; value=[true]], cleanWhenUnstable[attributes={}; value=[true]], cleanWhenFailure[attributes={}; value=[true]], cleanWhenNotBuilt[attributes={}; value=[true]], cleanWhenAborted[attributes={}; value=[true]], notFailBuild[attributes={}; value=[false]], cleanupMatrixParent[attributes={}; value=[false]], externalDelete[attributes={}; value=[]], disableDeferredWipeout[attributes={}; value=[false]]]]]], buildWrappers[attributes={}; value=[]]]]

Мой код, который работает ОК:

def triggered_job_config_file = JENKINS_HOME + '\\jobs\\' + RUNLIST[element] + '\\config.xml'
def xml_file = readFile triggered_job_config_file
def xml_file_contents = new XmlParser().parseText(xml_file)

Мой код, который не работает ОК:

Подойдите к коду:

def remote_scm_path = xml_file_contents.project.locations.hudson.scm.SubversionSCM_-ModuleLocation.remote
echo remote_scm_path.toString()

Подход A исключение:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field groovy.util.Node project

Код подхода B:

def remote_scm_path = xml_file_contents.remote
echo remote_scm_path.toString()

Исключение подхода B:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field groovy.util.Node remote

Подход C код:

echo "${xml_file_contents.project.locations.hudson.scm.SubversionSCM_-ModuleLocation.remote.text()}"

подход C исключение:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field groovy.util.Node project

Мой вопрос: кто-нибудь есть хорошая идея, как я могу перейти к значению "удаленного" в конфигурации. xml, который является следующим: http://LAPTOP/svn/localrepo/CCC/COMPONENT/RC

Спасибо!

Ответы [ 2 ]

0 голосов
/ 09 января 2020

Вот что вы можете добавить в консоль Groovy:

def xml_file = """<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description>Just a sample build job that should always be successful.</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.plugins.jira.JiraProjectProperty plugin="jira@3.0.11"/>
  </properties>
  <scm class="hudson.scm.SubversionSCM" plugin="subversion@2.12.2">
    <locations>
      <hudson.scm.SubversionSCM_-ModuleLocation>
        <remote>http://LAPTOP/svn/localrepo/CCC/COMPONENT/RC</remote>
        <credentialsId>someid</credentialsId>
      </hudson.scm.SubversionSCM_-ModuleLocation>
    </locations>
  </scm>
  <canRoam>true</canRoam>
  <buildWrappers/>
</project>"""

def xml_file_contents = new XmlParser().parseText(xml_file)
println xml_file_contents.scm.locations[0].children()[0].remote.text()

Это напечатает это для меня:

http://LAPTOP/svn/localrepo/CCC/COMPONENT/RC
0 голосов
/ 08 января 2020

Если вы можете использовать команду оболочки с выражением:

$ xidel -se '//remote/text()' file.xml

Вывод

http://LAPTOP/svn/localrepo/CCC/COMPONENT/RC
...