Home > Software engineering >  Write a File from Jenkins Groovy Script-Console
Write a File from Jenkins Groovy Script-Console

Time:10-13

I'm trying to find a way to write some content to a file using Jenkins Groovy Script-Console.

The use-case: Our CI manages some state-machine using a volume shared between all the nodes (which is in turn mapped to EFS). However - following the discovery of a bug in our CI groovy shared libs I found that some state files gone corrupt, and needed to write to them the corrected values, together with fixing the bug.

I could do that using ssh connection, however, as we're in process of abstracting out the workers we're trying to back off from that and manage ourselves only from the script-console and/or ci jobs.

I tried all these forms, all of which failed:

"echo 'the text' > /mnt/efs-ci-state/path/to/the-state-file.txt".execute().text
"""
cat <<<EOF > /mnt/efs-ci-state/path/to/the-state-file.txt
the text
EOF
""".execute().text
"bash -c 'echo the text > /mnt/efs-ci-state/path/to/the-state-file.txt'".execute().text
"echo 'the text' | tee /mnt/efs-ci-state/path/to/the-state-file.txt"

Can anybody show me the way to do that?

I'd also appreciate an explanation why the forms above won't work and/or a hint on how to execute commands that include piping and/or stdio directing from that script console.

Thanks :)

CodePudding user response:

["bash", "echo the text > /mnt/efs-ci-state/path/to/the-state-file.txt"].execute().text

or use plain groovy:

new File('/mnt/efs-ci-state/path/to/the-state-file.txt').text = "echo the text"

why not working:

  • options 1, 2, 4 : echo and piping is a feature of shell/bash - it will not work without bash

  • option 3 you have c echo and c is not a valid command

  • use array to execute complex commands and to separate bash from main part


i suggest you to use this kind of code if you want to capture and validate stderr

["bash", 'echo my text > /222/12345.txt'].execute().with{proc->
    def out=new StringBuilder(), err=new StringBuilder()
    proc.waitForProcessOutput(out, err)
    assert !err.toString().trim()
    return out.toString()
}
  • Related