繁体   English   中英

groovy 中的复杂模板

[英]Complex templating in groovy

我想做一些模板,我可以用 Jinja2 或 Jenkins 共享库中的 Helm 模板语言来做。

本质上,我想像这样动态呈现一个 pod 定义(用作 kubernetets 代理):

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 %>
    '''
}

我目前有一些意大利面条代码可以以功能方式通过字符串连接来执行此操作,但是我团队中的其他人(或 6 个月后的我)很难将他们的(我的)头围起来。 因此,我希望使用模板引擎渲染 pod,使其易于理解和维护。

从我在这里阅读的代码示例中,现有的模板引擎似乎没有这个功能,但我希望有人能证明我错了。

您可以使用内置的 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM