Reuse blocks of Groovy configuration code

12 views
Skip to first unread message

Alexey Savchkov

unread,
Apr 23, 2023, 12:37:20 PM4/23/23
to go-cd
Is there a way of declaring a block of Groovy configuration code and reusing it in several places of a Groovy configuration script? Say I have a  sequence of steps to fetch and unarchive an artifact:

stage('Stage1') {
  jobs {
    job('Job1') {
      tasks {
        fetchArtifact {
          pipeline = 'MyPipeline'
          stage = 'Build'
          job = 'Artifact1'
          source = 'util.tgz'
          file = true
        }
        bash { commandString = 'tar -xzf util.tgz' }

This sequence is common for all stages so I'd like to wrap it in a reusable object and call it in all relevant places, something like (not working, only for illustration):

def fetchUtil() {
  fetchArtifact {
    pipeline = 'MyPipeline'
    ...
  }
  bash { commandString = 'tar -xzf util.tgz' }
}

stage('Stage1') {
  jobs {
    job('Job1') {
      tasks {
        fetchUtil()
        bash { commandString = 'run some other commands' }

Can I do something like this? The best I can think of is to declare closures with attributes and pass them to individual fetchArtifact and bash tasks:
fetchArtifact fetchUtil
bash unarchiveUtil
but can I declare a sequence consisting of multiple tasks and reuse it later in the code?
I am aware of the task plugin but in my case it would be too complicated, all I'm looking for is how to combine a few available tasks into something Groovy can understand.

Thahks in advance.

Chad Wilson

unread,
Apr 24, 2023, 11:00:22 AM4/24/23
to go...@googlegroups.com
Sure!

You can use addAll() to add an array/collection of Tasks, or add() to add a single Task. You can see check out https://github.com/gocd/codesigning/blob/5288187ad876d99221a7f0863d5be5fc45fa63be/.gocd/build.gocd.groovy#L108-L120 for examples which re-uses the tasks defined here.

I'm no Groovy expert, but outside the DSL but believe you have to create typed objects explicitly, e.g new FetchArtifactTask(isFile, closure) in the above or pass in the context, e.g

image.png

and call with

image.png

Haven't tried it though, and there are probably more elegant ways :-)

-Chad

--
You received this message because you are subscribed to the Google Groups "go-cd" group.
To unsubscribe from this group and stop receiving emails from it, send an email to go-cd+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/go-cd/55988ad1-11f6-4879-8289-40d39cc4031en%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages