Issue
I would like to do some templating that I would be able to do with Jinja2 or the Helm templating language inside a Jenkins shared library.
Essentially I want to dynamically render a pod definition (to be used as the kubernetets agent) like so:
renderPod() {
return '''
apiVersion: v1
kind: Pod
metadata:
labels:
type: ephemeral-jenkins-agent
pipeline: generic_pipeline
spec:
containers:
- name: alpine
image: alpine:3.12.3
command:
- cat
tty: true
<% if dockerBuild() %>
- name: docker
image: docker:18.05-dind
securityContext:
privileged: true
volumeMounts:
- name: dind-storage
mountPath: /var/lib/docker
<% end %>
<% if dockerBuild() %>
volumes:
- name: dind-storage
emptyDir: {}
<% else %>
volumes: {}
<% end %>
'''
}
I currently have some spaghetti code 🍝 to do this with string concatenation in a functional way, but it'd be hard for others on my team (or me in 6 months) to wrap their (my) head around. Hence my desire to render the pod with a templating engine to make it easily understandable and easier to maintain.
From the code examples that I read here the existing templating engine doesn't appear to have this functionality, but I am hoping that someone will prove me wrong.
Solution
you could use built in SimpleTemplateEngine:
String renderTemplate(Map binding, String template) {
return new groovy.text.SimpleTemplateEngine().createTemplate(template).make(binding).toString()
}
def binding = [
dockerBuild: {
true
},
version: 'v1',
kind: 'Pod',
labels:[
type: 'ephemeral-jenkins-agent',
pipeline: 'generic_pipeline'
]
]
def template = '''\
apiVersion: ${version}
kind: <%= kind %>
metadata:
labels:
<% for(label in labels){ %>\
${label.key}: ${label.value}
<% } %>\
spec:
containers:
- name: alpine
image: alpine:3.12.3
command:
- cat
tty: true
<% if( dockerBuild() ){ %>\
- name: docker
image: docker:18.05-dind
securityContext:
privileged: true
volumeMounts:
- name: dind-storage
mountPath: /var/lib/docker
<% } %>\
<% if( dockerBuild() ){ %>\
volumes:
- name: dind-storage
emptyDir: {}
<% } else { %>\
volumes: {}
<% } %>\
'''
println renderTemplate(binding,template)
Answered By - daggett
Answer Checked By - Timothy Miller (JavaFixing Admin)