<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kobi Rosenstein on Medium]]></title>
        <description><![CDATA[Stories by Kobi Rosenstein on Medium]]></description>
        <link>https://medium.com/@cakeapps?source=rss-7232a3374397------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Aha7ZptBT8k57Rr8.</url>
            <title>Stories by Kobi Rosenstein on Medium</title>
            <link>https://medium.com/@cakeapps?source=rss-7232a3374397------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:58:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cakeapps/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Installing Rancher Harvester UI extension in an Airgap]]></title>
            <link>https://cakeapps.medium.com/installing-rancher-harvester-ui-extension-in-an-airgap-ac0b612cca28?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac0b612cca28</guid>
            <category><![CDATA[rancher]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[harvesters]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 12:47:37 GMT</pubDate>
            <atom:updated>2025-03-31T12:47:37.195Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/harvester/harvester-ui-extension/tree/gh-pages">GitHub - harvester/harvester-ui-extension at gh-pages</a></p><p>I tried the installation guide through the docs, but I kept getting the error ”failed to load code” when installing extensions throught the Rancher UI.</p><p>I created a local repo, cloned from github, pushed up to my new local repo and tried that — it didn’t work, with the above error message.</p><p>What I did to make it work was:</p><ol><li>SSH to a VM on the same lan as Rancher, get its IP address with ip a</li></ol><pre>git clone https://github.com/harvester/harvester-ui-extension.git<br>cd harvester-ui-extension<br>git checkout gh-pages<br>vi charts/harvester/1.0.0/templates/cr.yaml<br># set the endpoint to:<br>endpoint: http://&lt;vm ip address&gt;/extensions/harvester/1.0.0/<br># exit vim<br>sudo python3 -m http.server 80</pre><p>2. While the VM has python exposing the extension files, from a second SSH session:</p><pre>helm install -n cattle-ui-plugin-system harvester /home/ubuntu/charts/harvester/1.0.0/</pre><p>This works. Ideally, I would figure out why it doesn’t work from a local repo, but sometimes quick’n’dirty is needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac0b612cca28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Artifactory to Mirror a MAAS image repository]]></title>
            <link>https://cakeapps.medium.com/how-to-use-artifactory-to-mirror-a-maas-image-repository-9e146898c041?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e146898c041</guid>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[maaş]]></category>
            <category><![CDATA[artifactory]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 12:01:05 GMT</pubDate>
            <atom:updated>2025-02-19T12:01:05.109Z</atom:updated>
            <content:encoded><![CDATA[<p>Canonical’s tool for managing bare-metal servers, MaaS, needs access to images.maas.io , or else a local mirror.</p><p>For local mirroring, the <a href="https://maas.io/docs/how-to-manage-images#p-9030-use-a-local-mirror">official documentation</a> says to use the tool sstream-mirror , which is a smart tool which can check what parts of the images online have changed, and fetch only those changes, to a directory on the MaaS server, which you then need to expose with any web server (apache, nginx, during testing I even used python’s http.server !). However, if you are using Artifactory, you don’t need sstream-mirror at all, don;t need to maintain a server and can point MaaS directly at an Artifactory repository which is a remote of images.maas.io :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*xSOepemOSRgUWxMOg01FnA.png" /></figure><p>Then point Maas at this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*fuxjoFJuWAnLssO6RMaIFg.png" /></figure><p>That’s it, Artifactory will now always have the latest images from images.maas.io .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e146898c041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to conditionally hide a Jenkins Job parameter based on the value of another parameter]]></title>
            <link>https://cakeapps.medium.com/how-to-conditionally-hide-a-jenkins-job-parameter-based-on-the-value-of-another-parameter-df4762e54754?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/df4762e54754</guid>
            <category><![CDATA[self-service]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[groovy]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 17:23:00 GMT</pubDate>
            <atom:updated>2025-02-11T08:40:50.944Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a pretty commonly asked question, but the answer really isn’t straightforward.</p><p>The closest I could find was using Active Choices, and using HTML / Javascript to conditionally hide the parameter’s input, while not hiding the parameter name. While this is useful, it serves more a way to prevent user input than to really, truly hide a parameter — and sometimes, you just want to hide a parameter!</p><p>For example, let’s say I have a parameter called SERVER_ACTION, which returns a List of [&#39;stop&#39;,&#39;start&#39;,&#39;restart&#39;] , and another parameter called SERVER_STOP_GRACE_PERIOD . Assuming I selected stop , I will wait SERVER_STOP_GRACE_PERIOD for a server to gracefully shutdown before force powering off.</p><p>In the case that I selected something other than stop, I don’t want to even display the SERVER_STOP_GRACE_PERIOD parameter, since it is no longer relevant, and just presents visual clutter.</p><p>So, to fully and completely hide a parameter, we can use an Active Choices reactive Reference parameter of type ET_FORMATTED_HIDDEN_HTML , which will modify the page HTML based on the value of a referenced parameter. Naturally, I use my shared library to store this parameter, since it is pretty ugly to repeat each job, potentially multiple times.</p><h4>IMPORTANT:</h4><p>This code will only work if the monitor Parameter is a String , Boolean , or Choice parameter.</p><p>It can be adjusted to fit other input types by finding the relevant HTML elements from the web Inspector.</p><pre>// Standalone parameter<br>sharedParameters.conditionalParamHider(<br>    paramToHide: &#39;MY_CONDITIONAL_PARAM&#39;,<br>    monitorParam: &#39;PARAM_WHOSE_VALUE_IS_CHECKED&#39;,<br>    hideIfThisValue: &#39;Inputting or selecting this value in monitorParam will cause the param to be hidden.&#39;,<br>),</pre><pre>// Full example<br>// Jenkinsfile.groovy :<br>@Library(&#39;MySharedLibrary&#39;) _<br>AGENT_LABEL = &#39;linux &amp;&amp; build&#39; <br>pipeline {<br>    agent {<br>        label AGENT_LABEL<br>    }<br>    options {<br>        timestamps()<br>        timeout(time: 30, unit: &#39;MINUTES&#39;)<br>        ansiColor(&#39;xterm&#39;)<br>    }<br><br>    stages{<br>        stage(&#39;Setup Parameters&#39;) {<br>            steps {<br>                script {<br>                    println(&#39;INFO: This run will not run other stages&#39;)<br>                    currentBuild.description = &quot;REFRESH PARAMETERS&quot;<br>                    properties([<br>                        parameters([<br>                            sharedParameters.refreshParameters(),<br>                            sharedParameters.hiddenUsername(),<br>                            choice(name: &#39;SERVER_ACTION&#39;,<br>                                choices: [&#39;stop&#39;, &#39;start&#39;, &#39;restart&#39;],<br>                                description: &#39;If set to No, you must select an Environment, and then filter and choose specific resources in the Environment to delete.&#39;,<br>                            ),<br>                            string(name: &#39;SERVER_STOP_GRACE_PERIOD&#39;),<br>                            sharedParameters.conditionalParamHider(<br>                                paramToHide: &#39;SERVER_STOP_GRACE_PERIOD&#39;,<br>                                monitorParam: &#39;SERVER_ACTION&#39;,<br>                                hideIfThisValue: &#39;stop&#39;,<br>                            ),</pre><pre>// sharedParameters.groovy:<br>def conditionalParamHider(Map args) {<br>    // Required args:<br>        // paramToHide - this is the param which we will be able to hide conditionally based on the monitor param<br>        // monitorParam - this is the name of the param whose value will determine whether to hide a different param.<br>        // hideIfThisValue - this is the value of the param whose value will determine whether to hide a different param.<br><br>    String hiderScript = $/<br>    return &quot;&quot;&quot;<br>            &lt;style&gt;<br>                /* Initially hide in case it&#39;s already loaded */<br>                input[name=&quot;name&quot;][value=&quot;${args.paramToHide}&quot;] { display: none; }<br>            &lt;/style&gt;<br>            &lt;script&gt;<br>                function update${args.paramToHide}() {<br>                    var monitorNameField = document.querySelector(&#39;input[name=&quot;name&quot;][value=&quot;${args.monitorParam}&quot;]&#39;);<br>                    var field = document.querySelector(&#39;input[name=&quot;name&quot;][value=&quot;${args.paramToHide}&quot;]&#39;);<br><br>                    if (monitorNameField &amp;&amp; field) {<br>                        var tbody = field.closest(&#39;tbody&#39;);<br><br>                        // Get the value field (works for text inputs, dropdowns, and checkboxes)<br>                        var monitorValueField = monitorNameField.closest(&#39;div[name=&quot;parameter&quot;]&#39;).querySelector(&#39;input[name=&quot;value&quot;], select[name=&quot;value&quot;], input[type=&quot;checkbox&quot;]&#39;);<br><br>                        if (tbody &amp;&amp; monitorValueField) {<br>                            var monitorValue = &quot;&quot;;<br><br>                            // Handle checkboxes separately<br>                            if (monitorValueField.type === &quot;checkbox&quot;) {<br>                                monitorValue = monitorValueField.checked ? &quot;yes&quot; : &quot;no&quot;; // Convert checkbox state to yes/no<br>                            } else {<br>                                monitorValue = monitorValueField.value.trim().toLowerCase();<br>                            }<br><br>                            console.log(&quot;${args.monitorParam} detected value:&quot;, monitorValue);<br><br>                            if (monitorValue === &quot;${args.hideIfThisValue}&quot;.toLowerCase()) {<br>                                tbody.style.display = &#39;none&#39;;<br>                                console.log(&quot;${args.paramToHide} is hidden because ${args.monitorParam} is &#39;${args.hideIfThisValue}&#39;.&quot;);<br>                            } else {<br>                                tbody.style.display = &#39;&#39;;<br>                                console.log(&quot;${args.paramToHide} is visible.&quot;);<br>                            }<br>                        }<br>                    } else {<br>                        console.log(&quot;${args.monitorParam} or ${args.paramToHide} parameter not found.&quot;);<br>                    }<br>                }<br><br>                // Run immediately in case the element is already present<br>                update${args.paramToHide}();<br><br>                // Observe for dynamic changes (Jenkins UI updates)<br>                var observer = new MutationObserver(function(mutations, obs) {<br>                    update${args.paramToHide}();<br>                });<br><br>                observer.observe(document.body, { childList: true, subtree: true });<br><br>                // Listen for changes to the monitor parameter input, dropdown, or checkbox<br>                document.addEventListener(&#39;change&#39;, function(event) {<br>                    if (event.target &amp;&amp; (event.target.name === &quot;value&quot; || event.target.tagName === &quot;SELECT&quot; || event.target.type === &quot;checkbox&quot;)) {<br>                        update${args.paramToHide}();<br>                    }<br>                });<br>            &lt;/script&gt;<br>        &quot;&quot;&quot;<br>    /$.stripIndent().trim()<br><br>    return activeChoices.hiddenScriptParam(<br>       name: &quot;${args.paramToHide.toUpperCase()}_HIDER&quot;,<br>        script: hiderScript,<br>        referencedParameters: &quot;${args.monitorParam},${args.paramToHide}&quot;,<br>        choiceType: &#39;ET_FORMATTED_HIDDEN_HTML&#39;,<br>    )<br>}</pre><p>If you DO want the one that hides only the value, it’s set like this: (I have not bothered to wrap it like my other params, since I don’t use this form)</p><pre>[$class: &#39;DynamicReferenceParameter&#39;,<br>            choiceType: &#39;ET_FORMATTED_HTML&#39;,<br>            referencedParameters: &#39;MY_REFERENCED_VAR&#39;,<br>            omitValueField: true,<br>            name: &#39;MY_CONDITIONAL_VAR&#39;,<br>            script: [<br>                $class: &#39;GroovyScript&#39;,<br>                fallbackScript: [<br>                    classpath: [], <br>                    sandbox: false, <br>                    script: &quot;&quot;<br>                ],<br>                script: [<br>                    classpath: [], <br>                    sandbox: false, <br>                    script: &#39;&#39;&#39;\<br>                       if (MY_REFERENCED_VAR?.contains(&#39;value to check by&#39;)) {<br>                         // put whatever groovy you want. It needs to define a list:<br>                         List myList = []<br>  <br>                         // this is the part that returns the dropdown list<br>                         input_string = &quot;&lt;select name=&#39;value&#39;&gt;&quot;<br>                         myList.each{<br>                           input_string = input_string + &quot;&lt;option &gt;${it}&lt;/option&gt;&quot;<br>                         }<br>                         input_string += &quot;&lt;/select&gt;&quot;<br>                         return input_string<br>                        } else {<br>                            // Hide the input list by setting display none via HTML, and setting an ID we can target<br>                            return &quot;&quot;&quot;<br>                            &lt;style&gt;<br>                                #dynamic-my-conditional-var { display: none; }<br>                            &lt;/style&gt;<br>                            &lt;div id=&quot;dynamic-my-conditional-var&quot;&gt;&lt;/div&gt;<br>                            &quot;&quot;&quot;<br>                        }<br>                    &#39;&#39;&#39;.stripIndent()<br>                ]<br>            ]<br>        ]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df4762e54754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Choices Parameters as Jenkinsfile code, using wrapper functions]]></title>
            <link>https://cakeapps.medium.com/active-choices-parameters-as-jenkinsfile-code-using-wrapper-functions-a2b7d0bd642e?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2b7d0bd642e</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 13:01:06 GMT</pubDate>
            <atom:updated>2025-11-11T10:34:33.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Some params are simple to define as code, like:</p><pre>string(name: &lt;paramname&gt;, description: &#39;bla bla&#39;)</pre><p>Others are more complex, like hidden params, or, heaven save us, “Active Choices Reactive Reference params”.</p><p>The simple ones can be easily generated via Jenkins UI, but parameters which come from plugins generally cannot.</p><p>Once again, our shared library sharedParameters comes to the rescue!</p><p>A normal Active Choices Reactive Parameter of type Radio Button defined as code will look like this:</p><pre>[$class: &#39;CascadeChoiceParameter&#39;, <br>        choiceType: &#39;PT_RADIO&#39;,<br>        referencedParameters: &#39;&#39;, <br>        filterLength: 1, <br>        filterable: false, <br>        name: &#39;yes_orno_choice&#39;,<br>        description: &#39;Some choice&#39;,<br>        script: [<br>            $class: &#39;GroovyScript&#39;, <br>            fallbackScript: [<br>                classpath: [], <br>                sandbox: false, <br>                script:  &quot;&quot;<br>                ],<br>            script: [<br>                classpath: [], <br>                sandbox: false, <br>                script: &#39;&#39;&#39;<br>                return [&#39;yes&#39;, &#39;no&#39;]<br>                &#39;&#39;&#39;<br>            ]<br>        ]<br>    ]</pre><p>Why not wrap it?</p><pre>def radioButtonParam(Map args) {<br>    // Required args:<br>    //   name<br>    //   script<br><br>    // Optional args, with defaults:<br>    args.filterable = args.get(&#39;filterable&#39;, false)<br>    args.filterLength = args.get(&#39;filterLength&#39;, 1)<br>    args.description = args.get(&#39;description&#39;, &#39;&#39;)<br>    args.referencedParameters = args.get(&#39;referencedParameters&#39;, &#39;&#39;)<br><br><br>    [$class: &#39;CascadeChoiceParameter&#39;, <br>        choiceType: &#39;PT_RADIO&#39;,<br>        referencedParameters: args.referencedParameters, <br>        filterLength: args.filterLength, <br>        filterable: args.filterable, <br>        name: args.name,<br>        description: args.description,<br>        script: [<br>            $class: &#39;GroovyScript&#39;, <br>            fallbackScript: [<br>                classpath: [], <br>                sandbox: false, <br>                script:  &quot;&quot;<br>                ],<br>            script: [<br>                classpath: [], <br>                sandbox: false, <br>                script: args.script.stripIndent()<br>            ]<br>        ]<br>    ]<br>}</pre><p>Now, to use such a parameter all you need to do is:</p><pre>paramScript = &#39;&#39;&#39;<br>[&#39;new server&#39;, &#39;existing server&#39;]<br>&#39;&#39;&#39;<br>sharedParameters.radioButtonParam(name: &#39;choice_param_name&#39;, script: paramScript),</pre><p>Following this, here is a list of wrapper definitions you can use, and some usage examples. Note that I am using two layers of abstraction, one for the actual Active Choices parameters, as well as something that makes it easier to remember which to use.</p><h4>Hidden parameter:</h4><pre>// Hidden parameter: <br>// https://plugins.jenkins.io/hidden-parameter/<br><br>def hiddenParam(Map args) {<br>    [$class: &#39;WHideParameterDefinition&#39;,<br>      name: args.name,<br>      defaultValue: args.defaultValue,<br>    ]<br>}</pre><h4>Active Choices Parameters:</h4><pre>/*******************************************************************************************************<br>START OF PARAMETER CLASS FUNCTIONS:<br>Some params are simple to define as code, like string(name: &lt;paramname&gt;, description: &#39;bla bla&#39;)<br><br>But the complex ones, like active choices reactive reference, are huge undreadable blocks of groovy.<br>Here we simply wrap one of each type, and can pass a map of args to fill in the fields.<br><br>*******************************************************************************************************/<br><br>// All of the functions here set default args. Here we set ALL possible args for all functions, although most functions don&#39;t need all the args.<br>def setDefaultArgs(Map args) {<br>    args.name = args.get(&#39;name&#39;, &#39;&#39;)<br>    args.description = args.get(&#39;description&#39;, &#39;&#39;)<br>    args.referencedParameters = args.get(&#39;referencedParameters&#39;, &#39;&#39;)<br>    args.sandbox = args.get(&#39;sandbox&#39;, false)<br>    args.filterable = args.get(&#39;filterable&#39;, false)<br>    args.filterLength = args.get(&#39;filterLength&#39;, 1)<br>    args.omitValueField = args.get(&#39;omitValueField&#39;, true)<br>    args.fallbackScript =  args.get(&#39;fallbackScript&#39;, &#39;&#39;)<br><br>    return args<br>}<br><br>/*<br> Simple Active Choices Param.<br> Valid Choice Types:<br>    &#39;PT_SINGLE_SELECT&#39;<br>    &#39;PT_MULTI_SELECT&#39;<br>    &#39;PT_RADIO&#39;<br>    &#39;PT_CHECKBOX&#39;<br>*/<br>def param(Map args) {<br>    // Required args:<br>        //   name<br>        //   script<br>        //   choiceType<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    [$class: &#39;ChoiceParameter&#39;, <br>      choiceType: args.choiceType,<br>      referencedParameters: args.referencedParameters,<br>      description: args.description,<br>      name: args.name,<br>      script: [<br>        $class: &#39;GroovyScript&#39;,<br>        script: [<br>            classpath: [], <br>            sandbox: args.sandbox, <br>            script: args.script.stripIndent().trim()<br>        ],<br>        fallbackScript: [<br>            classpath: [], <br>            sandbox: args.sandbox, <br>            args.fallbackScript.stripIndent().trim()<br>        ]<br>      ], <br>    ]<br>}<br><br>/*<br> Active Choices Reactive Param.<br> Valid Choice Types:<br>    &#39;PT_SINGLE_SELECT&#39;<br>    &#39;PT_MULTI_SELECT&#39;<br>    &#39;PT_RADIO&#39;<br>    &#39;PT_CHECKBOX&#39;<br>*/<br>def reactiveParam(Map args) {<br>    // Required args:<br>        //   name<br>        //   script<br>        //   referencedParameters<br>        //   choiceType<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    [$class: &#39;CascadeChoiceParameter&#39;, <br>      choiceType: args.choiceType,<br>      referencedParameters: args.referencedParameters,<br>      description: args.description,<br>      name: args.name,<br>      script: [<br>        $class: &#39;GroovyScript&#39;,<br>        script: [   <br>          script: [<br>              classpath: [], <br>              sandbox: false, <br>              script: args.script<br>          ],<br>          fallbackScript: [<br>            classpath: [], <br>            sandbox: false, <br>            script: args.fallbackScript<br>          ]<br>        ]<br>    ]<br>}<br><br>/*<br> Active Choices Reactive Reference Param.<br> Valid Choice Types:<br>    &#39;ET_FORMATTED_HTML&#39;<br>    &#39;ET_FORMATTED_HIDDEN_HTML&#39;<br>    TODO: Add others<br>*/<br>def reactiveReferenceParam(Map args) {<br>    // Required args:<br>        //   name<br>        //   script<br>        //   referencedParameters<br>        //   choiceType<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    [$class: &#39;DynamicReferenceParameter&#39;, <br>        choiceType: args.choiceType,<br>        referencedParameters: args.referencedParameters,<br>        omitValueField: args.omitValueField,<br>        description: args.description,<br>        name: args.name,<br>        randomName: &#39;choice-parameter-245311171714082&#39;,<br>        script: [<br>            $class: &#39;GroovyScript&#39;,<br>            fallbackScript: [<br>                classpath: [], <br>                sandbox: args.sandbox, <br>                script: &quot;&quot;<br>            ],<br>            script: [<br>                classpath: [], <br>                sandbox: args.sandbox, <br>                script: args.script<br>            ]<br>        ]<br>    ]<br>}<br></pre><h4>Wrapper functions for Active Choices params:</h4><pre>def checkboxParam(Map args) {<br>    // Required args:<br>    //   name<br>    //   script<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    return param(<br>        choiceType: &#39;PT_CHECKBOX&#39;,<br>        name: args.name, <br>        script: args.script,<br>        description: args.description,<br>    )<br>}<br><br>def singleSelectParam() {<br>    // Required args:<br>        //   name<br>        //   script<br>        //   choiceType<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    return reactiveParam(<br>        choiceType: &#39;PT_SINGLE_SELECT&#39;,<br>        name: args.name,<br>        script: args.script, <br>    )<br><br>}<br><br>def reactiveSingleSelectParam(Map args) {<br>    // Required args:<br>        //   name<br>        //   script<br>        //   referencedParameters<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    return reactiveParam(<br>        choiceType: &#39;PT_SINGLE_SELECT&#39;,<br>        name: args.name,<br>        script: args.script, <br>        referencedParameters: args.referencedParameters,<br>    )<br>}<br><br>def reactiveMultiSelectParam(Map args) {<br>    // Required args:<br>        //   name<br>        //   script<br>        //   referencedParameters<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    return reactiveParam(<br>        choiceType: &#39;PT_MULTI_SELECT&#39;,<br>        name: args.name, <br>        script: args.script, <br>        referencedParameters: args.referencedParameters, <br>    )<br>}<br><br>def reactiveCheckboxParam(Map args) {<br>    // Required args:<br>    //   name<br>    //   script<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    return reactiveParam(<br>        choiceType: &#39;PT_CHECKBOX&#39;,<br>        name: args.name, <br>        script: args.script,<br>        description: args.description,<br>        referencedParameters: args.referencedParameters,<br>    )<br>}<br><br>def reactiveRadioButtonParam(Map args) {<br>    // Required args:<br>        //   name<br>        //   script<br>        //   referencedParameters<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    return reactiveParam(<br>        choiceType: &#39;PT_RADIO&#39;,<br>        name: args.name, <br>        script: args.script,<br>        description: args.description,<br>        referencedParameters: args.referencedParameters<br>    )<br>}<br><br>def hiddenScriptParam(Map args) {<br>    // Required args:<br>        //  script<br><br>    // Optional args, with defaults:<br>    setDefaultArgs(args)<br><br>    return activeChoicesReactiveReferenceParam(<br>        name: args.name,<br>        script: args.script,<br>        referencedParameters: referencedParameters,<br>        choiceType: &#39;ET_FORMATTED_HIDDEN_HTML&#39;,<br>    )<br>}</pre><h4>Usage examples:</h4><pre>// sharedParameters.groovy:<br><br>def hiddenUsername() {<br>   userNameScript = &#39;&#39;&#39;<br>    user = hudson.model.User.current().getId().toLowerCase()<br>    &quot;&quot;&quot;<br>        return &#39;&lt;input name=&quot;value&quot; value=&quot;${user}&quot; type=&quot;text&quot;&gt;&#39;<br>    &quot;&quot;&quot;<br>   &#39;&#39;&#39;<br>   activeChoices.hiddenScriptParam(name: &#39;USERNAME&#39;, script: userNameScript)<br>    //user = hudson.model.User.current().getId().toLowerCase()<br>    //hiddenParam(name: &#39;USERNAME&#39;, defaultValue: userNameScript)<br>}<br><br>def serversSelection() {<br>  serversScript = &#39;&#39;&#39;<br>  // some groovy here<br>  return myList<br>  &#39;&#39;&#39;<br>  activeChoices.reactiveCheckboxParam(name: name, script: serversScript, referencedParameters: referencedParameters)<br>}</pre><p>You can use these parameters anywhere you want, as I explain in my <a href="https://kcaps.medium.com/a-deep-dive-into-jenkins-job-parameters-as-code-with-both-runtime-and-ui-validation-e3f6565dfd54">post about sharedParameters</a>.</p><pre>// Jenkinsfile.groovy:<br><br>    stages {<br>        stage(&#39;Setup Parameters&#39;) {<br>            //run only if refresh_parameters checked<br>            when {<br>                environment (name: &#39;SKIP_STAGES&#39;, value: &#39;true&#39;) <br>            }<br>            steps {<br>                script {<br>                    println(&#39;INFO: This run will not run other stages&#39;)<br>                    currentBuild.description = &quot;REFRESH PARAMETERS&quot;<br>                    properties([<br>                        parameters([<br>                            sharedParameters.refreshParameters(),<br>                            sharedParameters.branchName(&#39;feature/cleanup-env&#39;),<br>                            sharedParameters.hiddenUsername(),<br>                            activeChoices.reactiveSingleSelectParam(name: &#39;INLINE_PARAM&#39;, script: &#39;return [1,2,3]&#39;, referencedParameters: &#39;USERNAME&#39;),<br>                        ].flatten())<br>                    ])<br>                    jenkinsGeneric.haltBuildWithSuccess(&#39;Refreshed parameters and quit&#39;)<br>                 }            <br>            }<br>        }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b7d0bd642e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global variables for Jenkins pipelines]]></title>
            <link>https://cakeapps.medium.com/global-variables-for-jenkins-pipelines-8a7e74a54793?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7e74a54793</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 19:06:00 GMT</pubDate>
            <atom:updated>2024-12-16T19:06:00.151Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever found yourself needing to be able to use the same variable over and over for many pipelines? Here’s how:</p><ol><li>Make a vars/globals.groovy file in your shared library</li><li>Put this in it:</li></ol><pre>#!/usr/bin/env groovy<br>import groovy.transform.Field<br><br>@Field final String GITHUB_URL = &#39;https://github.com/&#39;<br>@Field final String GITHUB_SLUG = &#39;k-caps&#39;</pre><p>3. Access the constant from your Jenkinsfiles:</p><pre>repoUrl = globals.GITHUB_URL + globals.GITHUB_SLUG</pre><p>You can access it from other files under vars the exact same way, too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7e74a54793" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A deep dive into Jenkins job parameters as code, with both runtime AND UI validation]]></title>
            <link>https://cakeapps.medium.com/a-deep-dive-into-jenkins-job-parameters-as-code-with-both-runtime-and-ui-validation-e3f6565dfd54?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f6565dfd54</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 18:26:38 GMT</pubDate>
            <atom:updated>2025-05-06T11:29:58.630Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Skip to the end of this post for just the code examples, without any of the explanations.</strong></h4><p>Let’s say you have a job which facilitates self service. You accept all sorts of parameters. One day, a developer opens a ticket saying “the job is broken! Please help asap!” So, like any good devops engineer, you drop your own work, spend some time debugging only to find… the parameter name was wrong. You fix the typo, run a new build and voila, the job passes, never having been broken at all. “What dumb users,” you giggle to yourself. “*I* would NEVER do something so stupid!”</p><p>Well, you will, and I will, and so will everyone else. That’s why we need code to validate all user inputs, and yep, that’s exactly what we’ll be doing today.</p><p>First off: You need to be using a Shared Library. These are key for code reusability in Jenkins, and parameters (and their validations) are no exception.</p><p>In case you aren’t already familiar, there is a directory called “vars” inside the shared library. Once you import the shared library to your pipeline, you can then access any variable or function defined in any .groovy file under the vars directory.</p><p>I won’t be explaining how to create and set up a shared library in Jenkins; there are already lots of guides covering this. Once you have the library set up (and be sure to use the modern SCM option when you set it up), you will be able to import the library.</p><p>To import the shared library to your Jenkinsfile, do:</p><pre>@Library(&#39;MySharedLibrary@library-repo-branch&#39;) _<br>pipeline { // As you can see, the library is the very first line in the file.</pre><p>The next step is setting parameters in the Jenkinsfile. Let’s take a moment and discuss how that’s done:</p><pre><br>environment {<br>        SKIP_STAGES = &quot;${params.REFRESH_PARAMETERS}&quot;<br>}<br>stages {<br>        stage(&#39;Setup Parameters&#39;) {<br>            //run only if refresh_parameters checked<br>            when {<br>                environment (name: &#39;SKIP_STAGES&#39;, value: &#39;true&#39;) <br>            }<br>            steps {<br>                script {<br>                    println(&#39;INFO: This run will not run other stages&#39;)<br>                    currentBuild.description = &quot;REFRESH PARAMETERS&quot;<br>                    properties([<br>                        parameters([<br>                           booleanParam(<br>                                  name: &#39;REFRESH_PARAMETERS&#39;,<br>                                  defaultValue: false,<br>                                  description: &#39;Read Jenkinsfile and exit.&#39;<br>                            ),<br>                            string(name: &#39;SERVER_NAME&#39;, required: true),<br>                            string(name: &#39;OS_IMAGE&#39;, defaultValue: &#39;ubuntu-24&#39;),<br><br>                        ]<br>                    ])<br>                    jenkinsGeneric.haltBuildWithSuccess(&#39;Refreshed parameters and quit&#39;)<br>               }            <br>            }<br>        }</pre><p>The most interesting thing in this first little snippet is the SKIP_STAGES environment variable. What happens is that when you go to the “build job” screen, the first parameter is a checkbox. If the checkbox is selected, and you build the job, the Setup Parameters stage runs. Because the parameter is set to false by default, and because the whole stage has a when clause, we can decide when to refresh our parameters, essentially loading them from the Jenkinsfile, while not wasting time doing this on each build.</p><p>The next thing of note is the function haltBuildWithSuccess at the end — read more about it in <a href="https://kcaps.medium.com/how-to-update-parameters-in-a-jenkins-job-then-abort-and-show-a-success-01e891217e2a">this pos</a>t. There’s quite a bit of overlap with this one, so here is the function, to be used anywhere you like:</p><pre><br>def haltBuildWithSuccess(String stopReason = &#39;Build halted programmatically with SUCCESS status&#39;) {<br>    currentBuild.rawBuild.@result = Result.SUCCESS<br>    def cause = new CauseOfInterruption.UserInterruption(stopReason)<br>    throw new FlowInterruptedException(Result.SUCCESS, false, cause)<br>}</pre><p>Okay, so now we know how to set parameters in the Jenkinsfile. Onwards, to the shared parameters!</p><p>In my shared library, I have a vars file called sharedParameters.groovy.</p><p>As one might assume, sharedParameters is a shared library vars file which returns parameters which are used in many jobs, and it looks a little something like this:</p><pre>def userSeparator(styling = &#39;color: whitesmoke; background: PaleVioletRed; text-align: center; font-weight: bold;&#39;, text = &#39;User Parameters&#39;){<br>    [$class: &#39;ParameterSeparatorDefinition&#39;,<br>        name: &#39;USER_HEADER&#39;,<br>        sectionHeader: text,<br>        separatorStyle: &#39;border: 0;&#39;,<br>        sectionHeaderStyle: styling<br>    ]<br>}<br><br>def refreshParameters() {<br>    [booleanParam(<br>        name: &#39;REFRESH_PARAMETERS&#39;,<br>        defaultValue: false,<br>        description: &#39;Read Jenkinsfile and exit.&#39;<br>    )]<br>}<br><br>def branchName(String defaultBranch = &#39;main&#39;) {<br>    [<br>        [<br>            string(<br>                name: &#39;BRANCH_NAME&#39;,<br>                defaultValue: defaultBranch,<br>                description: &#39;Which branch of Jenkins pipeline to deploy&#39;<br>            )<br>        ],<br>        paramValidator(&#39;BRANCH_NAME&#39;)<br>    ]<br>}<br><br>def username() {<br>    [<br>        [$class: &#39;ChoiceParameter&#39;, <br>            choiceType: &#39;PT_SINGLE_SELECT&#39;,<br>            filterLength: 1, <br>            filterable: false, <br>            name: &#39;USERNAME&#39;, <br>            script: [<br>                $class: &#39;GroovyScript&#39;, <br>                script: [<br>                    classpath: [], <br>                    sandbox: false, <br>                    script: &#39;&#39;&#39;\<br>                        try {<br>                          &quot;[hudson.model.User.current().getId().toUpperCase()]&quot;<br>                         }                    <br>                        catch(Exception e) {<br>                          return [e.toString()]<br>                        }<br>                     &#39;&#39;&#39;<br>                ]<br>            ]<br>        ],<br>        paramValidator(&#39;USERNAME&#39;)<br>    ]<br>}</pre><p>Naturally, there are a whole lot more parameters here in real life.</p><p>Remember that these vars files are simply groovy files containing functions. Each function defined in the sharedParameters file simply returns a list element including a valid parameter. Why a list, you may ask? Because ChoiceParameters return their selection as a list, even if only a single element.</p><p>With all that in mind, we can now move all of our reusable parameters into the sharedParameters file, and call them from our Jenkinsfiles:</p><pre>    stages{<br>        stage(&#39;Setup parameters&#39;) {<br>            //run only if REFRESH_PARAMETERS checked<br>            when {<br>                environment (name: &#39;SKIP_STAGES&#39;, value: &#39;true&#39;) <br>            }<br>            steps {<br>                script {<br>                    println(&#39;INFO: This run will not run other stages&#39;)<br>                    currentBuild.description = &quot;REFRESH PARAMETERS&quot;<br>                    properties([<br>                        parameters([<br>                            sharedParameters.refreshParameters(),<br>                            sharedParameters.branchName(&#39;main&#39;), // specifies what branch of a jenkinsfile will be run<br>                            string(name: &#39;SERVER_NAME&#39;),    <br>                            ].flatten())<br>                        ])<br>                    jenkinsGeneric.haltBuildWithSuccess(&#39;Refreshed parameters and quit&#39;)<br>                 }            <br>              }<br>          }</pre><p>Okay, so we have set our parameters as callable functions in a shared library, and now we want to validate them.</p><p>We have another file under vars, and this one is called paramValidator.groovy.</p><p>This file is a bit complicated, so before we get into exactly what’s in it and how it works, let’s go over what we need to happen at this step:</p><ol><li>Fail Early.</li></ol><p>We don;t want a situation where an incorrect parameter can cause an error after a few minutes of runtime — we want the job to fail immediately. Ideally, it would not even run at all. Therefore, the first step is at the UI level — we need a way to prevent the user from even running the build at all, if the parameters are incorrect.</p><p>We do this by adding a DynamicReferenceParameter immediately after the parameter which we are validating. This parameter is invisible, it has no name or value, but it can still be used reactively to the parameter we are validating. Here’s what it looks like in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*Li1lrTwZFOjar_qJ5Z40KQ.png" /><figcaption>An example of a parameter which passes validation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*BUstETp1v7zq7giVAySv4Q.png" /><figcaption>An example of a parameter value which does not fit the requirements</figcaption></figure><p>Not only does this immediately tell the user that something is wrong, we also set the invisible parameter’s type to ET_FORMATTED_HTML, which we use to hide the build button from the UI.</p><p>That’s all well and good, but what if the user calls the job programmatically, or hits rebuild and changes the parameters? That’s where runtime validations come in.</p><p>The way that the paramValidator file works is that it has a call function, which runs if the file is called with no specific function. This function returns the invisible HTML parameter, and it looks like this:</p><pre>def call(String paramName) {<br>    return [$class: &#39;DynamicReferenceParameter&#39;, <br>        choiceType: &#39;ET_FORMATTED_HTML&#39;,<br>        referencedParameters: paramName,<br>        omitValueField: true,<br>        description: &#39;&#39;,<br>        name: &#39;&#39;,<br>        randomName: &#39;choice-parameter-245311171714082&#39;,<br>        script: [<br>            $class: &#39;GroovyScript&#39;,<br>            fallbackScript: [<br>                classpath: [], <br>                sandbox: false, <br>                script: &quot;&quot;<br>            ],<br>            script: [<br>                classpath: [], <br>                sandbox: true, <br>                script: validateParams(paramName, &#39;UI&#39;)<br>            ]<br>        ]<br>    ]<br>}</pre><p>Notice how other than setting it to be mostly invisible and giving it a type, we also call a function validateParams(). This is where the magic happens.</p><pre><br>@Field final String hideBuildButton = &#39;&lt;style&gt;.jenkins-button--primary, .submit-button.primary button { display: none; }&lt;/style&gt;&#39;<br>@Field final String hiddenInput = &quot;&lt;input type=&#39;hidden&#39; name=&#39;value&#39; value=&#39;XXXXXXXXXXXXXXXXXXXXXXXXXXXX&#39;&gt;&quot;<br><br>def validateParams(String paramName, String paramSender=&#39;code&#39;) {<br>    String paramScript<br>    String okMsg <br>    String errorMsg <br>    String paramValidityChecker<br>    switch (paramName) {<br><br>        case &quot;BRANCH_NAME&quot;:<br>            okMsg = &#39;Branch name looks OK&#39;<br>            errorMsg = &#39;No branch selected.&#39;<br>            paramValidityChecker = &quot;if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; )&quot;<br>            break<br><br>        case &quot;USERNAME&quot;:<br>            okMsg = &#39;Username seems OK&#39;<br>            errorMsg = &#39;No Username. Are you logged in?&#39;<br>            paramValidityChecker =  &quot;if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; )&quot;<br>            break<br>    }<br>    // Checks if param is OK as defined above in the switch case. If not, it will immediately return an error with the message we set earlier. <br><br>    // This is run only from the parameters stage, which means that the logic in paramScript gets run BEFORE runtime, within the referenced parameters<br>    if ( paramSender == &#39;UI&#39; ) {<br>        // This is a string builder and we directly continue the &#39;if&#39; statement which is stored in $paramValidityChecker, and concat both the curly braces and the logic.<br>        paramScript = &quot;&quot;&quot;\<br>            okMsg = &#39;$okMsg&#39;<br>            $paramValidityChecker { <br>                errorMsg = &quot;$errorMsg&quot;<br>        &quot;&quot;&quot;.stripIndent() // The rest of the logic and the closing brace are in the return statement below.<br><br>        return &quot;&quot;&quot;<br>            $paramScript<br>                return \&quot;\&quot;\&quot;\<br>                    $hideBuildButton<br>                    &lt;span style=&#39;color:red&#39;&gt;&amp;#10060; \$errorMsg&lt;/span&gt;<br>                    $hiddenInput<br>                \&quot;\&quot;\&quot;.trim().stripIndent()<br>            }<br>            return \&quot;\&quot;\&quot;<br>                &lt;span style=&#39;color:green&#39;&gt;&amp;#9989; \$okMsg&lt;/span&gt;<br>                $hiddenInput<br>            \&quot;\&quot;\&quot;<br>        &quot;&quot;&quot;.stripIndent()<br>    } else {<br>        // This is run by any validation not in the parameters stage - IE these get run at runtime and not before it.<br><br>        paramValue = &quot;${params[paramName]}&quot;  // This is to get the value of the parameter, since in a &#39;code&#39; we don&#39;t have access to the referenced paramneter like we do with &#39;UI&#39;<br>        paramValidityChecker = paramValidityChecker.replaceAll(paramName, &quot;&#39;&quot; + paramValue + &quot;&#39;&quot;) // We actually only want to check the value, we don&#39;t care about the parameter name<br>  <br>        // This finalizes the conditional logic, and finishes using the conditional string we built earlier in the switch/case<br>        def runtimeValidityEvaluator = &quot;&quot;&quot;<br>            $paramValidityChecker {<br>                return(&quot;errorMsg&quot;)<br>            } else {<br>                return(&quot;okMsg&quot;)<br>            }<br>        &quot;&quot;&quot;  <br>        env.errorMsg = errorMsg<br>        // this is what actually evaluates whether the parameter is valid or not, and prints an OK message if the parameter didn&#39;t throw an error<br>        Eval.me(runtimeValidityEvaluator) == &#39;okMsg&#39; ? println(okMsg) : error(env.errorMsg)<br><br>    }    <br>}</pre><p>Whenever this function is called, it accepts an argument paramName. This argument is checked against a switch case statement. Based on the parameter name we receive, we apply different validations, and output different error and success messages. However, at this point, we have not actually executed the validation code, only set it into a variable called paramValidityChecker. This is a string, which will eventually make its way into the script section of the job parameter.</p><p>In this example, we have only done very simple validations. Further on’ Ill also discuss more complex ones. For now, let’s understand how this switch is used.</p><p>As mentioned, paramValidityChecker is simply a string containing groovy code. Notice that it is not actually syntactically correct — the code cuts out immediately after an if clause, without even closing it.</p><p>After adding our cases to the switch, we need to validate the value we received. Again, this same validation must be applied both at runtime, and before runtime, at the parameter selectionBuild with Parameters screen.</p><p>The call function is the one that gets run from the UI, and it passes the second argument which is needed by validateParams() — essentially telling it not to apply the validation, but rather return it to the parameter. In this case, that means it is never run at all — only when a user clicks “build with parameters” will the validator code be run. The relevant piece of the function is this:</p><pre>paramScript = &quot;&quot;&quot;\<br>            okMsg = &#39;$okMsg&#39;<br>            $paramValidityChecker { <br>                errorMsg = &quot;$errorMsg&quot;<br>        &quot;&quot;&quot;.stripIndent()</pre><p>Here, we’ve simply continued building our if code block from the switch statement from above (isng the BRANCH_NAME param as an example):</p><pre>okMsg = &#39;Branch name looks OK&#39;<br>errorMsg = &#39;No branch selected.&#39;<br>paramValidityChecker = &quot;if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; )&quot;</pre><p>This way, paramScript will contain:</p><pre>okMsg = &#39;$okMsg&#39;<br>if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; ) { <br>  errorMsg = &quot;$errorMsg&quot;</pre><p>At this point our code is beginning to take shape, but we still aren’t done. We still have to do something with the error message:</p><pre>return &quot;&quot;&quot;<br>            $paramScript<br>                return \&quot;\&quot;\&quot;\<br>                    $hideBuildButton<br>                    &lt;span style=&#39;color:red&#39;&gt;&amp;#10060; \$errorMsg&lt;/span&gt;<br>                    $hiddenInput<br>                \&quot;\&quot;\&quot;.trim().stripIndent()<br>            }<br>            return \&quot;\&quot;\&quot;<br>                &lt;span style=&#39;color:green&#39;&gt;&amp;#9989; \$okMsg&lt;/span&gt;<br>                $hiddenInput<br>            \&quot;\&quot;\&quot;<br>        &quot;&quot;&quot;.stripIndent()</pre><p>See all the escaping? That’s because we are generating code which will eventually be the parameter’s script.</p><p>The first return statement will return the entire if block, containing the final string, which is now fully built, looking like this:</p><pre>okMsg = &#39;$okMsg&#39;<br>if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; ) { <br>  errorMsg = &quot;$errorMsg&quot;<br>  return &quot;&quot;&quot;<br>    $hideBuildButton<br>    &lt;span style=&#39;color:red&#39;&gt;&amp;#10060; $errorMsg&lt;/span&gt;<br>    $hiddenInput<br>  }<br>  return &quot;&quot;&quot;<br>    &lt;span style=&#39;color:green&#39;&gt;&amp;#9989; $okMsg&lt;/span&gt;<br>      $hiddenInput<br>  &quot;&quot;&quot;<br></pre><p>As you can see, the final generated code is quite readable, and this is the script within the invisible, reactive parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*JgkrMpGsiytlXjkNSD5YRw.png" /></figure><p>Now, on to runtime validation. As you’ll recall, paramValidator accepts a flag which can contain ‘code’ or ‘ui’. We’ve already seen how UI is handled. So what happens if we want to run the validation during the build?</p><p>This is the “else” clause in the middle of paramValidator, and this one is similar but easier to understand.</p><p>We don’t need to build convoluted statements with HTML or anything, we just need to execute the code. So first we finish building the if clause string from the switch case above, into a variable called runtimeValidityEvaluator…</p><pre><br>if ( paramSender == &#39;UI&#39; ) {<br>  // discussed above<br>}<br>else {<br>// This is run by any validation not in the parameters stage - IE these get run at runtime and not before it.<br><br>paramValue = &quot;${params[paramName]}&quot;  // This is to get the value of the parameter, since in a &#39;code&#39; we don&#39;t have access to the referenced paramneter like we do with &#39;UI&#39;<br>paramValidityChecker = paramValidityChecker.replaceAll(paramName, &quot;&#39;&quot; + paramValue + &quot;&#39;&quot;) // We actually only want to check the value, we don&#39;t care about the parameter name<br><br>// This finalizes the conditional logic, and finishes using the conditional string we built earlier in the switch/case<br>def runtimeValidityEvaluator = &quot;&quot;&quot;<br>    $paramValidityChecker {<br>        return(&quot;errorMsg&quot;)<br>    } else {<br>        return(&quot;okMsg&quot;)<br>    }<br>&quot;&quot;&quot;  <br></pre><pre>// runtimeValidityEvaluator will contain:<br>okMsg = &#39;$okMsg&#39;<br>if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; ) { <br>  return(&quot;errorMsg&quot;)<br>} <br>else {<br>   return(&quot;okMsg&quot;)<br>}<br>// Notice that we return string literals, which indicate the result</pre><p>…And then we run it!</p><pre>env.errorMsg = errorMsg<br>// this is what actually evaluates whether the parameter is valid or not, and prints an OK message if the parameter didn&#39;t throw an error<br>Eval.me(runtimeValidityEvaluator) == &#39;okMsg&#39; ? println(okMsg) : error(env.errorMsg)</pre><p>If the runtimeValidityEvaluator equals the literal string okMsg, we just print that message. If not, we throw an error right away.</p><p>Therefore, to validate a parameter at runtime, all we need to do is this:</p><pre>stage(&#39;Parameters Check&#39;) {<br>          steps {<br>              script {<br>                  paramValidator.emptyParameterChecker([&#39;PARAM_NAME&#39;, &#39;OTHER_PARAM_NAME&#39;])<br>                  paramValidator(&#39;BRANCH_NAME&#39;)<br>                  <br>          }<br>      }<br>  }</pre><p>It is important to note that some code will not run inside the Eval statement, because it is a very limited environment which does not have access to the jenkins classpath — so you can’t import things like Jenkins.model, or hudson.* . So, for code that uses that kind of thing, you need to build the paramValidityChecker conditionally:</p><pre>            paramValidityChecker = &#39;&#39;&#39;\<br>                &#39;&#39;&#39;<br>                    if (paramSender == &#39;UI&#39;) {<br>                    paramValidityChecker += &#39;&#39;&#39;<br>                import hudson.model.User<br>                import jenkins.*<br>                import jenkins.model.*<br>                import hudson.*<br>                import hudson.model.*<br><br>                def getApiToken (credId) {<br>                    tokenCredId = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(<br>                    com.cloudbees.plugins.credentials.Credentials.class,<br>                    Jenkins.instance,<br>                    null,<br>                    null<br>                    ).find{it.id == &quot;${credId}&quot;}<br>                    return tokenCredId.secret.getPlainText()<br>                }<br>                <br>                rancherToken = getApiToken(&quot;&#39;&#39;&#39; + globals.RANCHER_RND_ADMIN_BEARER_TOKEN_CRED_ID + &#39;&#39;&#39;&quot;)                    <br>                bitbucketToken = getApiToken(&quot;&#39;&#39;&#39; + globals.BUILDUSER_BITBUCKET_API_TOKEN_CRED_ID + &#39;&#39;&#39;&quot;)<br>                &#39;&#39;&#39;<br>                } else {             <br>                    withCredentials([<br>                        string(credentialsId: globals.RANCHER_RND_ADMIN_BEARER_TOKEN_CRED_ID, variable: &#39;rancherToken&#39;),<br>                        string(credentialsId: globals.BUILDUSER_BITBUCKET_API_TOKEN_CRED_ID, variable: &#39;bitbucketToken&#39;)<br>                    ]) {<br>                        paramValidityChecker += &quot;&quot;&quot;<br>                rancherToken = &#39;$rancherToken&#39;<br>                bitbucketToken = &#39;$bitbucketToken&#39;<br>                        &quot;&quot;&quot;<br>                    }<br>                }</pre><p>The emptyParameterChecker function is not complex; it just iterates over a list of parameters and makes sure they are not empty. This is mainly only useful for parameters which are not in the shared library.</p><pre>def emptyParameterChecker(List paramsToCheck) { <br>    env.errorMsg = &quot;&quot;<br><br>    paramsToCheck.each { paramName -&gt;<br>        def paramValue = params.&quot;${paramName}&quot; // Access the parameter dynamically by its name, even though we didn&#39;t actually pass the value to this function<br><br>        if (!paramValue || paramValue.toString().isEmpty() || paramValue == &#39;null&#39;) {<br>            env.errMsg += &quot;The parameter ${paramName} is empty or undefined.\n&quot;<br>        }<br>    }<br>    if (env.errorMsg) {<br>        error(env.errorMsg)<br>    }<br>}</pre><p>Some notes:</p><p>With paramValidator, we are eventually returning a list of parameters consisting of the actual parameter, and the invisible validator parameter. So we need to flatten the Jenkinsfile’s list of parameters:</p><pre>properties([<br>                        parameters([<br>                            sharedParameters.refreshParameters(),<br>                            sharedParameters.branchName(&#39;feature/DVPS-9717-helm-vm&#39;),<br>                            sharedParameters.userSeparator(&#39;color: whitesmoke; background: PaleVioletRed; text-align: center; font-weight: bold;&#39;),<br>                            sharedParameters.username(),<br>                            string(name: &#39;SERVER_TYPE&#39;, defaultValue: &#39;srv&#39;),<br>                            paramValidator.unhideBuild()<br>                        ].flatten())<br>                    ])</pre><p>Another important thing to note is that if any parameters fail validation, you won’t be able to run the job to refresh parameters because the build button will be hidden. That’s why we have yet another function in paramValidator:</p><pre>// This allows the &quot;build&quot; button to appear when &quot;refresh_parameters&quot; is selected<br>def unhideBuild() {<br>    return [$class: &#39;DynamicReferenceParameter&#39;, <br>        choiceType: &#39;ET_FORMATTED_HTML&#39;,<br>        referencedParameters: &#39;REFRESH_PARAMETERS&#39;,<br>        omitValueField: true,<br>        description: &#39;&#39;,<br>        name: &#39;&#39;,<br>        randomName: &#39;choice-parameter-245311171714082&#39;,<br>        script: [<br>            $class: &#39;GroovyScript&#39;,<br>            fallbackScript: [<br>                classpath: [],<br>                sandbox: false, <br>                script: &quot;&quot;<br>            ],<br>            script: [<br>                classpath: [], <br>                sandbox: true, <br>                script: &#39;&#39;&#39;\<br>                    if (REFRESH_PARAMETERS) {<br>                        return &#39;&lt;style&gt;.jenkins-button--primary, .submit-button.primary button { display: block; }&lt;/style&gt;&#39;<br>                &#39;&#39;&#39;<br>            ]<br>        ]<br>    ]<br>}</pre><p>Lastly, we can also have complex validations, not only the simple ones we’ve use as examples. Pretty much any groovy code is OK here:</p><pre>case &quot;RAM&quot;:<br>    okMsg = &#39;Requested RAM OK&#39;<br>    errorMsg = &#39;RAM must be an integer between 1 and 32.&#39;<br>    paramValidityChecker = &quot;&quot;&quot;\<br>        boolean isValidNumber(resource) {<br>            def isNum = ( resource.isInteger() ) ? true : false<br>            if (!isNum) {<br>                return false<br>            } else if ( (resource.toInteger() &gt; 0) &amp;&amp; (resource.toInteger() &lt; 32) ) {<br>                return true<br>            } else {<br>                return false<br>            }<br>        }<br>        if ( ${paramName} == &#39;&#39; || !isValidNumber(${paramName}) )<br>    &quot;&quot;&quot;.stripIndent() <br>    break<br><br>case &quot;IP&quot;:<br>    okMsg = &#39;IP Address looks OK&#39;<br>    errorMsg = &#39;IP address was incorrectly formatted&#39;<br>    paramValidityChecker =  &quot;&quot;&quot;\<br>        boolean validIPAddress(String ipAddress) {<br>            def regexPattern = ~/\\d+\\.\\d+\\.\\d+\\.\\d+/<br>            def matcher = (ipAddress =~ regexPattern)<br>            def containsIP = ( matcher.find() ) ? true : false<br>            return containsIP<br>        }<br>        if ( ${paramName} == &#39;&#39; || !validIPAddress(${paramName}) )<br>    &quot;&quot;&quot;.stripIndent() <br>    break<br></pre><p>I’ve even gone so far as to use a binary on the jenkins master to dynamically validate whether a selected project is valid:</p><pre>       case &quot;RANCHER_PROJECT&quot;:<br>            paramValidityChecker = &#39;&#39;&#39;\<br>                import hudson.model.User<br>                import jenkins.*<br>                import jenkins.model.*<br>                import hudson.*<br>                import hudson.model.*             <br>                bearerTokenCredId = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(<br>                    com.cloudbees.plugins.credentials.Credentials.class,<br>                    Jenkins.instance,<br>                    null,<br>                    null<br>                ).find{it.id == &quot;&#39;&#39;&#39; + globals.POC_RANCHER_ADMIN_BEARER_TOKEN_CRED_ID +&#39;&#39;&#39;&quot;}<br><br>                bearerToken = bearerTokenCredId.secret.getPlainText()      <br>                rancherCli = &quot;&#39;&#39;&#39; + globals.RANCHER_CLI_PATH  + &#39;&#39;&#39;&quot;<br>                rancherUrl = &quot;&#39;&#39;&#39; + globals.POC_RANCHER_URL + &#39;&#39;&#39;&quot;<br>                rancherClusterId = &quot;&#39;&#39;&#39; + globals.POC_RANCHER_CLUSTER_ID + &#39;&#39;&#39;&quot;<br>                rancherSystemProjectId = &quot;&#39;&#39;&#39; + globals.POC_RANCHER_SYSTEM_PROJECT_ID + &#39;&#39;&#39;&quot;<br>                rancherContext = &quot;${rancherClusterId}:${rancherSystemProjectId}&quot;<br>                rancherLoginCommand = &quot;${rancherCli} login ${rancherUrl} --token ${bearerToken} --skip-verify --context ${rancherContext}&quot;<br>                &#39;&#39;&#39;+&quot;&quot;&quot;<br>                rancherLoginCommand.execute()<br>                def getProjectsOutputCommand = rancherCli + &#39; projects list | grep -v -e &quot;Default&quot; -e &quot;System&quot; -e &quot;ID&quot; | awk \\&#39;{print \$2}\\&#39;&#39;<br>                def projects = [&#39;bash&#39;, &#39;-c&#39;, getProjectsOutputCommand].execute()in.text<br>                def projectsList = projects.toLowerCase().split(&#39;\\n&#39;).toList()                 <br>                if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; || !projectsList.contains(${paramName}.toLowerCase()) )<br>            &quot;&quot;&quot;.stripIndent()<br>            okMsg = &#39;Valid Project&#39;<br>            errorMsg = &#39;The Project ${&#39; + paramName + &quot;.toLowerCase()} is not present in your projects: \${projectsList.toString()}&quot;<br>            break</pre><p>You can really implement any custom logic you want.</p><h3>TLDR complete code samples:</h3><p>vars/paramValidator.groovy :</p><pre>#!/usr/bin/env groovy<br><br>import groovy.transform.Field<br><br><br>def emptyParameterChecker(List paramsToCheck) { <br>    env.errorMsg = &quot;&quot;<br><br>    paramsToCheck.each { paramName -&gt;<br>        def paramValue = params.&quot;${paramName}&quot; // Access the parameter dynamically by its name, even though we didn&#39;t actually pass the value to this function<br><br>        if (!paramValue || paramValue.toString().isEmpty() || paramValue == &#39;null&#39;) {<br>            env.errMsg += &quot;The parameter ${paramName} is empty or undefined.\n&quot;<br>        }<br>    }<br>    if (env.errorMsg) {<br>        error(env.errorMsg)<br>    }<br>}<br><br>@Field final String hideBuildButton = &#39;&lt;style&gt;.jenkins-button--primary, .submit-button.primary button { display: none; }&lt;/style&gt;&#39;<br>@Field final String hiddenInput = &quot;&lt;input type=&#39;hidden&#39; name=&#39;value&#39; value=&#39;XXXXXXXXXXXXXXXXXXXXXXXXXXXX&#39;&gt;&quot;<br> <br>def validateParams(String paramName, String paramSender=&#39;code&#39;) {<br>    String paramScript<br>    String okMsg <br>    String errorMsg <br>    String paramValidityChecker<br>    switch (paramName) {<br><br>        case &quot;BRANCH_NAME&quot;:<br>            okMsg = &#39;Branch name looks OK&#39;<br>            errorMsg = &#39;No branch selected.&#39;<br>            paramValidityChecker = &quot;if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; )&quot;<br>            break<br><br>        case &quot;USERNAME&quot;:<br>            okMsg = &#39;Username seems OK&#39;<br>            errorMsg = &#39;No Username. Are you logged in?&#39;<br>            paramValidityChecker =  &quot;if ( ${paramName} == &#39;&#39; || ${paramName} == &#39;error&#39; )&quot;<br>            break<br><br>        default:<br>            errorMsg = &quot;The parameter &#39;${paramName}&#39; was passed to the shared library at paramValidator.validateParams(), but does not have an associated validation. Please add a case for it.&quot;<br>            paramValidityChecker = &quot;if ( true )&quot;<br>            break<br>    }<br><br>    // Checks if param is OK as defined above in the switch case. If not, it will immediately return an error with the message we set earlier. <br><br>    // This is run only from the parameters stage, which means that the logic in paramScript gets run BEFORE runtime, within the referenced parameters<br>    if ( paramSender == &#39;UI&#39; ) {<br>       <br>        // This is a string builder and we directly continue the &#39;if&#39; statement which is stored in $paramValidityChecker, and concat both the curly braces and the logic.<br>        paramScript = &quot;&quot;&quot;\<br>            okMsg = &#39;$okMsg&#39;<br>            $paramValidityChecker { <br>                errorMsg = &quot;$errorMsg&quot;<br>        &quot;&quot;&quot;.stripIndent() // The rest of the logic and the closing brace are in the return statement below.<br><br>        return &quot;&quot;&quot;<br>            $paramScript<br>                return \&quot;\&quot;\&quot;\<br>                    $hideBuildButton<br>                    &lt;span style=&#39;color:red&#39;&gt;&amp;#10060; \$errorMsg&lt;/span&gt;<br>                    $hiddenInput<br>                \&quot;\&quot;\&quot;.trim().stripIndent()<br>            }<br>            return \&quot;\&quot;\&quot;<br>                &lt;span style=&#39;color:green&#39;&gt;&amp;#9989; \$okMsg&lt;/span&gt;<br>                $hiddenInput<br>            \&quot;\&quot;\&quot;<br>        &quot;&quot;&quot;.stripIndent()<br><br>    } else {<br>        // This is run by any validation not in the parameters stage - IE these get run at runtime and not before it.<br><br>        paramValue = &quot;${params[paramName]}&quot;  // This is to get the value of the parameter, since in a &#39;code&#39; we don&#39;t have access to the referenced paramneter like we do with &#39;UI&#39;<br>        paramValidityChecker = paramValidityChecker.replaceAll(paramName, &quot;&#39;&quot; + paramValue + &quot;&#39;&quot;) // We actually only want to check the value, we don&#39;t care about the parameter name<br>  <br>        // This finalizes the conditional logic, and finishes using the conditional string we built earlier in the switch/case<br>        def runtimeValidityEvaluator = &quot;&quot;&quot;<br>            $paramValidityChecker {<br>                return(&quot;errorMsg&quot;)<br>            } else {<br>                return(&quot;okMsg&quot;)<br>            }<br>        &quot;&quot;&quot;  <br>        env.errorMsg = errorMsg<br>        // this is what actually evaluates whether the parameter is valid or not, and prints an OK message if the parameter didn&#39;t throw an error<br>        Eval.me(runtimeValidityEvaluator) == &#39;okMsg&#39; ? println(okMsg) : rejectThisBuild(env.errorMsg)<br><br>    }    <br>}<br><br>// This allows the &quot;build&quot; button to appear when &quot;refresh_parameters&quot; is selected<br>def unhideBuild() {<br>    return [$class: &#39;DynamicReferenceParameter&#39;, <br>        choiceType: &#39;ET_FORMATTED_HTML&#39;,<br>        referencedParameters: &#39;REFRESH_PARAMETERS&#39;,<br>        omitValueField: true,<br>        description: &#39;&#39;,<br>        name: &#39;&#39;,<br>        randomName: &#39;choice-parameter-245311171714082&#39;,<br>        script: [<br>            $class: &#39;GroovyScript&#39;,<br>            fallbackScript: [<br>                classpath: [],<br>                sandbox: false, <br>                script: &quot;&quot;<br>            ],<br>            script: [<br>                classpath: [], <br>                sandbox: true, <br>                script: &#39;&#39;&#39;\<br>                    if (REFRESH_PARAMETERS) {<br>                        return &#39;&lt;style&gt;.jenkins-button--primary, .submit-button.primary button { display: block; }&lt;/style&gt;&#39;<br>                    }<br>                &#39;&#39;&#39;<br>            ]<br>        ]<br>    ]<br>}<br><br>def rejectThisBuild(errorMsg) {<br>   currentBuild.description = &quot;Rejected due to parameter validation&quot;<br> error(env.errorMsg)<br>}<br><br>def call(String paramName) {<br>    return [$class: &#39;DynamicReferenceParameter&#39;, <br>        choiceType: &#39;ET_FORMATTED_HTML&#39;,<br>        referencedParameters: paramName,<br>        omitValueField: true,<br>        description: &#39;&#39;,<br>        name: &#39;&#39;,<br>        randomName: &#39;choice-parameter-245311171714082&#39;,<br>        script: [<br>            $class: &#39;GroovyScript&#39;,<br>            fallbackScript: [<br>                classpath: [], <br>                sandbox: false, <br>                script: &quot;&quot;<br>            ],<br>            script: [<br>                classpath: [], <br>                sandbox: true, <br>                script: validateParams(paramName, &#39;UI&#39;)<br>            ]<br>        ]<br>    ]<br>}</pre><p>vars/sharedParameters.groovy :</p><pre>#!/usr/bin/env groovy<br><br>def userSeparator(styling = &#39;color: whitesmoke; background: PaleVioletRed; text-align: center; font-weight: bold;&#39;, text = &#39;User Parameters&#39;){<br>    [$class: &#39;ParameterSeparatorDefinition&#39;,<br>        name: &#39;USER_HEADER&#39;,<br>        sectionHeader: text,<br>        separatorStyle: &#39;border: 0;&#39;,<br>        sectionHeaderStyle: styling<br>    ]<br>}<br><br>def refreshParameters() {<br>    [booleanParam(<br>        name: &#39;REFRESH_PARAMETERS&#39;,<br>        defaultValue: false,<br>        description: &#39;Read Jenkinsfile and exit.&#39;<br>    )]<br>}<br><br>def branchName(String defaultBranch = &#39;master&#39;) {<br>    [<br>        [<br>            string(<br>                name: &#39;BRANCH_NAME&#39;,<br>                defaultValue: defaultBranch,<br>                description: &#39;Which branch of Jenkins pipeline to deploy&#39;<br>            )<br>        ],<br>        paramValidator(&#39;BRANCH_NAME&#39;)<br>    ]<br>}</pre><p>Jenkinsfile :</p><pre>@Library(&#39;MySharedLibrary&#39;) _<br>pipeline {<br>    agent {<br>        label &#39;buildmachines&#39;<br>    }<br>    options {<br>        timestamps()<br>        timeout(time: 3, unit: &#39;MINUTES&#39;)<br>        ansiColor(&#39;xterm&#39;)<br>    }<br><br>    environment {<br>        SKIP_STAGES = &quot;${params.REFRESH_PARAMETERS}&quot;<br>    }<br>    stages {<br>        stage(&#39;Setup Parameters&#39;) {<br>            //run only if refresh_parameters checked<br>            when {<br>                environment (name: &#39;SKIP_STAGES&#39;, value: &#39;true&#39;) <br>            }<br>            steps {<br>                script {<br>                    println(&#39;INFO: This run will not run other stages&#39;)<br>                    currentBuild.description = &quot;REFRESH PARAMETERS&quot;<br>                    properties([<br>                        parameters([<br>                            sharedParameters.refreshParameters(),<br>                            sharedParameters.branchName(&#39;feature/using-shared-library&#39;),<br>                            sharedParameters.userSeparator(&#39;color: whitesmoke; background: PaleVioletRed; text-align: center; font-weight: bold;&#39;),<br>                            sharedParameters.username(),<br>                            string(name: &#39;SERVER_NAME&#39;, defaultValue: &#39;srv&#39;),<br>                            string(name: &#39;SERVER_ID&#39;, defaultValue: &#39;srv&#39;),<br>                            sharedParameters.k8sProject(),<br>                            paramValidator.unhideBuild()<br>                        ].flatten())<br>                    ])<br>                    jenkinsGeneric.haltBuildWithSuccess(&#39;Refreshed parameters and quit&#39;)<br>       }            <br>            }<br>        }<br>        stage(&#39;Parameters Check&#39;) {<br>            steps {<br>                script {<br>                    paramValidator.emptyParameterChecker([&#39;SERVER_NAME&#39;, &#39;SERVER_ID&#39;])<br>                    paramValidator(&#39;K8S_PROJECT&#39;)<br>                    // Error if CPU or RAM is not an integer within the allowed range. Cuuently both are set to 1-32 but each can be changed separately.<br>                    paramValidator(&#39;RAM&#39;)<br>                    paramValidator(&#39;CPU&#39;)<br>                }<br>            }<br>        }<br><br>        stage(&#39;Run actual pipeline stages here...&#39;) {<br>        }<br>    }<br>    post {<br>        always {<br>            println(&#39;Cleaning up&#39;)<br>            cleanWs()<br>        }   <br>    }<br>}<br>        </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f6565dfd54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily get Jenkins secret files into the workspace]]></title>
            <link>https://cakeapps.medium.com/easily-get-jenkins-secret-files-into-the-workspace-69fa09372b22?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/69fa09372b22</guid>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 11:19:41 GMT</pubDate>
            <atom:updated>2024-12-16T13:56:04.449Z</atom:updated>
            <content:encoded><![CDATA[<p>According to the <a href="https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#secret-files">documentation</a>, using a secret file from the credentials should be pretty straightforward, but when I tried it, i kept getting erros about invalid characters, that didn’t even appear in my code.</p><p>The problem was this comment:</p><pre>// The MY_KUBECONFIG environment variable will be assigned<br>// the value of a temporary file.  For example:<br>// /home/user/.jenkins/workspace/cred_test@tmp/secretFiles/546a5cf3-9b56-4165-a0fd-19e2afe6b31f/kubeconfig.txt</pre><p>It is easy to assume from this example that all you need to do is:</p><pre> mySecretFile = credentials(&#39;secret-file-id&#39;)</pre><p>But, as it turns out, this returns a file handler object and NOT the path of the file like the docs claim:</p><pre>@credentials(&lt;anonymous&gt;=secret-file-id)</pre><p>The cause was that mySecretFile was being used in a script { block and not the environment { section. <a href="https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#handling-credentials">https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#handling-credentials</a>.</p><p>But, in my case I just wanted a quick way to randomly add a secret file from anywhere in the pipeline? For instance, what if I want to iterate over a list of files? and so I added a new function to my shared library’s generalFunctions var file:</p><pre>def secretFileToWorkspace(Map args) {<br>    args.secretFileCredId    = args.get(&#39;secretFileCredId&#39;, args.secretFileCredId)<br>    args.secretFileLocalName = args.get(&#39;secretFileLocalName&#39;, args.secretFileLocalName)<br><br>    withCredentials([file(credentialsId: args.secretFileCredId, variable: &#39;fileContent&#39;)]) {<br>        sh(&quot;cat $fileContent &gt; $args.secretFileLocalName&quot;)<br>    }<br>}</pre><p>And to call from within a pipeline:</p><pre>generalFunctions.secretFileToWorkspace(secretFileCredId: &#39;secret-file-id&#39;, secretFileLocalName: &#39;my_secret_file.txt&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69fa09372b22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily get variables from a downstream Jenkins job]]></title>
            <link>https://cakeapps.medium.com/how-to-easily-get-variables-from-a-downstream-jenkins-job-191fd7e454e8?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/191fd7e454e8</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[groovy]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 13:21:16 GMT</pubDate>
            <atom:updated>2024-11-07T13:21:16.149Z</atom:updated>
            <content:encoded><![CDATA[<p>I was absolutely stunned by how hard this seems.</p><p>But the answer isn’t difficult, just hard to find.<br>First, let’s define the problem.</p><p>Say you have many jobs, each which performs one discrete action.<br>To tie the various actions together, you create a “parent” job, which triggers all the “action” jobs, which we’ll call children.</p><p>Say one of the child jobs sets a variable which we need to later use in a different child job, for instance, if a job creates a dynamically named object such as a VM, and a later job connects to the new VM and performs some Ansible task on it.</p><p>Because child jobs will each create and clean their own workspace, we can use environment variables in the child, which we can then catch with the parent.</p><p>For example, let’s say the child job creates a variable called newServerIP, we can do (in any part of the child job):</p><p>env.newServerIP = newServerIP</p><p>To then retrieve the value, the simplest way I have found is as follows:</p><pre>stage(&#39;Run child job&#39;) {<br>    steps {<br>        childJob = build job: &#39;Folder/job_name&#39;,<br>        parameters: [<br>            string(name: &#39;NAME&#39;, value: &#39;Kobi&#39;),<br>        ]<br>        newServerIP = childJob?.buildVariables?.newServerIP <br>        println(newServerIP)</pre><p>Naturally, we can then do whatever we want with this variable, including sending it down to sibling jobs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191fd7e454e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to update Parameters in a Jenkins job, then abort and show a success.]]></title>
            <link>https://cakeapps.medium.com/how-to-update-parameters-in-a-jenkins-job-then-abort-and-show-a-success-01e891217e2a?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/01e891217e2a</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[groovy]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 06:20:05 GMT</pubDate>
            <atom:updated>2024-08-04T06:20:05.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you have a Jenkinsfile with user parameters. You don’t always want to set the parameters each time you run the job since they only change rarely. And when you do change them, it’s annoying having to run the job and then abort it just to refresh the parameter inputs. WHat if the job could do it on its own?</p><p>To solve this annoyance, I like to have a stage which only sets parameters, and then have a checkbox parameter that runs that stage in the beginning of the Job, with a conditional:</p><pre>    stages{<br>        stage(&#39;Setup parameters&#39;) {<br>            //run only if REFRESH_PARAMETERS checked<br>            when {<br>                environment (name: &#39;SKIP_STAGES&#39;, value: &#39;true&#39;) <br>            }<br>            steps {<br>                script {<br>                    println(&#39;INFO: This run will not run other stages&#39;)<br>                    currentBuild.description = &quot;REFRESH PARAMETERS&quot;<br>                    properties([<br>                        parameters([<br>                            sharedParameters.refreshParameters(),<br>                            sharedParameters.branchName(&#39;main&#39;), // specifies what branch of a jenkinsfile will be run<br>                            string(name: &#39;SERVER_NAME&#39;),    <br>                            ].flatten())<br>                        ])<br>                    jenkinsGeneric.haltBuildWithSuccess(&#39;Refreshed parameters and quit&#39;)<br>                 }            <br>              }<br>          }</pre><p>As one might assume, sharedParameters is a shared library vars file which returns parameters which are used in many jobs:</p><pre>def userSeparator(styling = &#39;color: whitesmoke; background: PaleVioletRed; text-align: center; font-weight: bold;&#39;, text = &#39;User Parameters&#39;){<br>    [$class: &#39;ParameterSeparatorDefinition&#39;,<br>        name: &#39;USER_HEADER&#39;,<br>        sectionHeader: text,<br>        separatorStyle: &#39;border: 0;&#39;,<br>        sectionHeaderStyle: styling<br>    ]<br>}<br><br>def refreshParameters() {<br>    [booleanParam(<br>        name: &#39;REFRESH_PARAMETERS&#39;,<br>        defaultValue: false,<br>        description: &#39;Read Jenkinsfile and exit.&#39;<br>    )]<br>}<br><br>def branchName(String defaultBranch = &#39;master&#39;) {<br>    [<br>        [<br>            string(<br>                name: &#39;BRANCH_NAME&#39;,<br>                defaultValue: defaultBranch,<br>                description: &#39;Which branch of Jenkins pipeline to deploy&#39;<br>            )<br>        ],<br>        paramValidator(&#39;BRANCH_NAME&#39;)<br>    ]<br>}</pre><p>By the way, paramValidator is super useful, but that is a topic for another post.</p><p>Notice the function at the end of the parameters stage:</p><pre>jenkinsGeneric.haltBuildWithSuccess(&#39;Message&#39;)</pre><p>This function jenkinsGeneric is where the magic happens:</p><pre><br>def haltBuildWithSuccess(String stopReason = &#39;Build halted programmatically with SUCCESS status&#39;) {<br>    currentBuild.rawBuild.@result = Result.SUCCESS<br>    def cause = new CauseOfInterruption.UserInterruption(stopReason)<br>    throw new FlowInterruptedException(Result.SUCCESS, false, cause)<br>}</pre><p>Now when you check the REFRESH_PARAMETERS checkbox, the build will read the Jenkinsfile and abort while showing the run as a success.</p><p>Big thanks to <a href="https://stackoverflow.com/users/10025322/barel-elbaz">https://stackoverflow.com/users/10025322/barel-elbaz</a> For helping me out with the haltBuildWithSuccess function!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01e891217e2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using shared libraries with post stages in a Jenkins pipeline]]></title>
            <link>https://cakeapps.medium.com/using-shared-libraries-with-post-stages-in-a-jenkins-pipeline-8d449c080543?source=rss-7232a3374397------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d449c080543</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[groovy]]></category>
            <dc:creator><![CDATA[Kobi Rosenstein]]></dc:creator>
            <pubDate>Wed, 08 May 2024 11:13:22 GMT</pubDate>
            <atom:updated>2024-05-16T10:29:27.310Z</atom:updated>
            <content:encoded><![CDATA[<p>When using Jenkins, over time, as you begin to use many jobs, you want to start moving things to shared libraries.</p><p>For me, I have a standardized way of doing error handling in my pipelines, and it always uses the post directive with different checks for failure and aborted .</p><p>The problem is, this error handling is a large and messy block of code that must get re-used in each pipeline — so naturally the correct thing to do is use a shared library. Here’s the code:</p><ol><li>Wrap each stage in a try/catch block:</li></ol><pre>stage(&#39;do things&#39;) {<br>  steps {<br>    script {<br>      try {<br>        // does things<br>      }<br>      catch(Exception ex) {<br>        env.error_message = ex.toString()<br>        error(&#39;Failed to do things&#39;)<br>      }<br>     }                    <br>   }<br> }</pre><p>2. Add a post step that uses the raised exception:</p><pre>  post {<br>    always {<br>      script {<br>        post_actions.always()<br>        post_actions.shutdown(env.error_message)<br>      }<br>    }<br>  } </pre><p>3. The shared library should be stored in the vars directory as post_actions.groovy:</p><pre>#!/usr/bin/env groovy<br>import groovy.transform.Field<br><br>@Field MATCHER_ERRORS_LIST = &quot;.*fatal.*|.*failed.*|.*ERROR.*|.*FAILED.*|.*UNREACHABLE.*&quot;<br>@Field MATCHER_ABORTED_LIST = &quot;&#39;.*Aborted by .*&#39;&quot;<br><br><br>def always() {<br>    cleanWs()<br>}<br><br>def success() {<br>    script {<br>        println &#39;\033[0;32mFinished Successfully\033[0m&#39;<br>    }<br>}   <br><br>def aborted(String matcher, String error_message){<br>    echo &#39;This job has been aborted.&#39;<br>    //If aborted by user<br>    if (matcher &amp;&amp; matcher != &#39;null&#39; ) {<br>        matcher_aborted = matcher.split(&#39;lastmatch=&#39;)[1].split(&#39;0m&#39;)[1].split(&#39;]&#39;)[0]<br>        println &quot;\033[0;31mAborted by User: &#39;${matcher_aborted}&#39; \033[0m&quot;<br>    }<br>    else {<br>        //If there is an error message<br>        if (error_message &amp;&amp; error_message != &#39;null&#39;) { <br>            println &quot;\033[0;31mfatal | ERROR | ABORTED | ${error_message} \033[0m&quot;<br>        }<br>        else {<br>            println &#39;\033[0;31mDEBUG: error_message either null or undefined&#39;<br>        }<br>    }<br>}<br><br>def failure(String matcher, String error_message) {<br>    //if there is an error<br>    if (matcher &amp;&amp; matcher != &#39;null&#39; ) {<br>        matcher_error = matcher.split(&#39;lastmatch=&#39;)[1].replace(&#39;]&#39;, &#39;&#39;)<br>        matcher_error = matcher_error.substring(matcher_error.indexOf(&#39; &#39;) + 1)<br>        println(&#39;This job has failed. Exception error:&#39;)<br>        sh &quot;#!/bin/sh -e\n &quot; + &quot;echo &#39;${matcher_error}&#39;&quot;<br>    }<br>    else {<br>        //if Aborted By Another Jenkins Job<br>        if (error_message.toString().contains(&#39;FlowInterruptedException&#39;)) {<br>            currentBuild.result = &#39;ABORTED&#39;<br>            echo &#39;This job was aborted.&#39;<br>            println(&quot;\033[0;31m&#39;FlowInterruptedException&#39; - Aborted by another Jenkins job. Result is ABORTED\033[0m&quot;)<br>        }<br>        else {<br>            echo &#39;This job has been aborted.&#39;<br>            echo &#39;Exception error:&#39;<br>            println &#39;\033[0;31mfatal | ERROR | &#39; + error_message + &#39;\033[0m&#39;<br>        }<br>    }<br>}<br><br>def shutdown(String error_message) {<br>    switch (currentBuild.result) {<br>        case &#39;SUCCESS&#39;:<br>            success()<br>            break<br>        case &#39;FAILURE&#39;:<br>            matcher = manager.getLogMatcher(MATCHER_ERRORS_LIST).toString()<br>            failure(matcher, error_message)           <br>            break<br>        case &#39;ABORTED&#39;:<br>            matcher = manager.getLogMatcher(MATCHER_ABORTED_LIST).toString()<br>            aborted(matcher, error_message)  <br>            break          <br>    }<br>}</pre><p>As always, if I update the code, you’ll find it at my Github:</p><p><a href="https://github.com/k-caps/scripts/blob/master/jenkins/error_handling.md">scripts/jenkins/error_handling.md at master · k-caps/scripts</a></p><p>Hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d449c080543" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>