0

I have below stage in jenkinsfile where the param name is derived from for loop "i" value: How to interpolate at run time the parameter value derived at run time

stage ('Create new part'){
          steps {
             script{
                 sh "mkdir ${WORKSPACE}/inventories && touch ${WORKSPACE}/inventories/hosts"
                  for (i in (["db", "pr", "pl", "ad", "lo", "log", "jm", "se", "fo", "me", "he"]) ) {
                       if ("${params."'$i'_instances"}" == "3" && "${params."'$i'_disksize"}" > "80") {
                          sh "echo 'Entered if loop'" 
                          sh "echo '['$i'-servers]'>> ${WORKSPACE}/inventories/hosts"
                          for (j=1; j<=params.$i_instances; j++) {
                              sh "echo '${params.project_name}-${params.environment_name}-${$i_prefix}-$j target_fs="${params.$i_FS_TYPE}" percentage_fs="{params.$i_fs_percentage}"' >> ${WORKSPACE}/inventories/hosts"
                            }
                         }   
                   }
                }
            }
          }

user312307
  • 153
  • 6
  • 21
  • What’s the error that you see? Why not simply use `if (params."${i}_instances" == "3"...`? Single quotes around `i` will prevent interpolation. – Dibakar Aditya Nov 06 '19 at 20:40
  • @DibakarAditya I get this error ```groovy.lang.MissingPropertyException: No such property: i_instances for class: WorkflowScript``` for line ```if (params."${i_instances}" == "3" && params."${i_disksize}" != "80")``` – user312307 Nov 06 '19 at 20:44
  • Close the curly braces after `i`. – Dibakar Aditya Nov 06 '19 at 20:47
  • @DibakarAditya . Thanks a lot, it works :) How can I convert param value to int to use > 0r < operator? – user312307 Nov 06 '19 at 20:48
  • You can use the `string.toInteger()` method. See https://stackoverflow.com/questions/1713481/groovy-string-to-int. – Dibakar Aditya Nov 06 '19 at 20:50
  • @DibakarAditya Thanks a lot, I appreciate. I get through that stage but get error for ``` sh "echo '${params.project_name}-${params.environment_name}-env."${i}_prefix"-${j} target_fs='params."${i}_FS_TYPE"' percentage_fs='params."${i}_fs_percentage"'' >> ${WORKSPACE}/inventories/hosts" ``` and error is ```/var/jenkins/workspace/disk@tmp/durable-f2d29cc8/script.sh: line 1: unexpected EOF while looking for matching `''``` – user312307 Nov 06 '19 at 21:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/201974/discussion-between-user312307-and-dibakar-aditya). – user312307 Nov 06 '19 at 21:10

1 Answers1

2

Single quotes around Groovy GStrings prevent interpolation. Use if (params."${i}_instances" == "3" && params."${i}_disksize" != "80") instead.

Dibakar Aditya
  • 3,893
  • 1
  • 14
  • 25