Can we calculate the agent element ?

18 views
Skip to first unread message

Charles Moulliard

unread,
Apr 23, 2021, 9:24:41 AM4/23/21
to Jenkins Users
Hi

The following Jenkins pipeline script is not working and we will get as error

ERROR
WorkflowScript: 20: Expected string literal @ line 20, column 11.
       agent checkEnvironment()
             ^

WorkflowScript: 20: Only "agent none", "agent any" or "agent {...}" are allowed. @ line 20, column 5.
       agent checkEnvironment()

CODE

@Library('snowdrop-lib') _

def checkEnvironment() {
  stage("main") {
    node {
      if (fileExists('/var/run/secrets/kubernetes.io')) {
        AGENT_DEF = """kubernetes {
                            |  defaultContainer 'jnlp'
                            |  yaml libraryResource('./podTemplates/multi-containers.yml')
                            |}""".stripMargin()
      } else {
        AGENT_DEF = "label any"
      }
      return AGENT_DEF
    }
  }  
}

pipeline {
    agent checkEnvironment()
    ...

Question: Can we do something like this ? If yes - How ? Example ?

Cheers

Charles

JonathanRRogers

unread,
Apr 23, 2021, 4:04:28 PM4/23/21
to Jenkins Users
It looks like you're trying to allow the same pipeline to run using either Kubernetes agents or some other type of agent. Is that realistic? In my experience, there are a number of things one has to pay attention to in a Kubernetes agent, especially if it's a multi-container pod.

I'm not sure how flexible a declarative pipeline can be, but it is certainly possible to have a scripted pipeline determine which type of node in which to run steps at run time. The node() syntax takes a string expression. You can pass a block to a method which conditionally calls the block inside a podTemplate() or not.
Reply all
Reply to author
Forward
0 new messages