Search code examples
rubyjenkinscucumberjenkins-cli

Pass Jenkins variable to Ruby scripts


Currently i'm trying to echo the name of the user that trigger a build using

$BUILD_USER_ID

from the user vars plugin, but from there i'm unsure as to how to pass this into my ruby scripts, i did this in a batch commmand:

set USER= $BUILD_USER_ID

and this is what i have in my ruby file:

ENV['USER']

But it return weird bunch of letters, which im guesing is the user name in the slave node i'm using to run the job.

is there something i'm missing?


Solution

  • You can combine your plugin with the envinject plugin to inject environment variables in your Jenkins job.

    I've created a jenkins job and installed both plugins. I've ticked the "Set jenkins user build variables". I've also ticked: "Inject environment variables to the build process" and define inside the "Properties Content":

    USER = $BUILD_USER_ID
    

    This will create a new environment variable USER with as content the content of the variable BUILD_USER_ID (which is created by the user env plugin).

    To test:

    I've created a file.rb which contains my ruby code to print an environment variable (just in the shell).

    # write script
    echo "#!/usr/bin/env ruby" > file.rb
    echo "# Print some variables" >> file.rb
    echo "puts ENV['BUILD_USER_ID']" >> file.rb
    
    # execute script
    ruby file.rb
    

    Output:

    [EnvInject] - Injecting as environment variables the properties content 
    USER=$BUILD_USER_ID
    
    [EnvInject] - Variables injected successfully.
    [test] $ /bin/sh -xe /tmp/jenkins3544234152865572985.sh
    + echo #!/usr/bin/env ruby
    + echo # Print some variables
    + echo puts ENV['USER']
    + ruby file.rb
    admin
    Finished: SUCCESS