Saturday, November 13, 2021

[SOLVED] Regular expression to fetch the Jenkins node workDir

Issue

I am trying to fetch the secret and workdir of a jenkins node in a script.

curl -L -s -u user:password -X GET https://cje.example.com/computer/jnlpAgentTest/slave-agent.jnlp

This gives

<jnlp codebase="https://cje.example.com/computer/jnlpAgentTest/" spec="1.0+">
    <information>
        <title>Agent for jnlpAgentTest</title>
        <vendor>Jenkins project</vendor>
        <homepage href="https://jenkins-ci.org/"/>
    </information>
    <security>
        <all-permissions/>
    </security>
    <resources>
        <j2se version="1.8+"/>
        <jar href="https://cje.example.com/jnlpJars/remoting.jar"/>
    </resources>
    <application-desc main-class="hudson.remoting.jnlp.Main">
        <argument>b8c80148ce36de10c9358384fac9e28fbba941055a9a6ab2277e75ddc29a8744</argument>
        <argument>jnlpAgentTest</argument>
        <argument>-workDir</argument>
        <argument>/tmp/jnlpAgenttest</argument>
        <argument>-internalDir</argument>
        <argument>remoting</argument>
        <argument>-url</argument>
        <argument>https://cje.example.com/</argument>
    </application-desc>
</jnlp>

Here I want to fetch the secret and workDir, secret can be fetched using this command

curl -L -s -u admin:password -H "Jenkins-Crumb:dac7ce5614f8cb32a6ce75153aaf2398" -X GET https://owood.ci.cloudbees.com/computer/jnlpAgentTest/slave-agent.jnlp | sed "s/.*<application-desc main-class=\"hudson.remoting.jnlp.Main\"><argument>\([a-z0-9]*\).*/\1/"
b8c80148ce36de10c9358384fac9e28fbba941055a9a6ab2277e75ddc29a8744

But I couldn't find a way to fetch workDir value, here it is /tmp/jnlpAgenttest which exists immediately after the tag -workDir


Solution

You can use

sed -n '/-workDir/{n;s/.*>\([^<>]*\)<.*/\1/p}'
sed -n -e '/-workDir/{n' -e 's/.*>\([^<>]*\)<.*/\1/p' -e '}'

See the online demo.

Details:

  • /-workDir/ - find the line with -workDir tag
  • n - reads the next line into pattern space discarding the previous one read
  • s/.*>\([^<>]*\)<.*/\1/ - matches any text up to >, then captures into Group 1 any zero or more chars other than < and >, then matches < and the rest of the string and replaces with Group 1 value
  • p - print the result of substitution.


Answered By - Wiktor Stribiżew