我有一个处理模板文件(例如XML文件)的管道作业,并且需要在使用渲染的文件之前用作业参数替换文件中的一些变量,但目前看来,我似乎找不到任何干净的方法我只是使用shell脚本并使用sed来逐一替换每个变量。

这是一个示例XML模板文件:

<?xml version='1.0' encoding='UTF-8'?>
<rootNode>
    <properties>
        <property1>${property1}</property1>
        <property2>${property2}</property2>
        <property3>${property3}</property3>
    </properties>
</rootNode>

我希望将模板文件中的“变量”替换为工作参数$property1$property2$property3
这是我今天正在做的事情:
sh  "sed -i 's/@property1@/${property1}/' '${templateFile}'" +
    "sed -i 's/@property2@/${property2}/' '${templateFile}'" +
    "sed -i 's/@property3@/${property3}/' '${templateFile}'"

...但是我觉得这很丑...在Jenkins中是否有用于模板化文件的东西,例如Jinja2(或任何模板框架)会做什么?

最佳答案

这是我找到的解决方案:我使用以下文件创建了一个全局共享库:
resources/report.txt.groovy(这是我的模板文件):

Hello from ${job}!
vars/helpers.groovy:
import groovy.text.StreamingTemplateEngine

def renderTemplate(input, variables) {
  def engine = new StreamingTemplateEngine()
  return engine.createTemplate(input).make(variables).toString()
}

然后,在管道中,添加了以下步骤:
variables = [ "job": currentBuild.rawBuild.getFullDisplayName() ]
template = libraryResource('report.txt.groovy')
output = helpers.renderTemplate(template, variables)

这会生成一个存储在output变量中的字符串,其内容如下:
Hello from SIS Unix Automation Testing » myjob » master #29!

其中SIS Unix Automation Testing » myjob » master是我的Multibranch Pipeline作业的全名。

当然,您可以使用此变量的内容进行任何操作,例如将其写到文件中或通过电子邮件发送,并且可以使用xml文件模板或所需的任何文件类型,而不仅仅是txt。

请注意,您将需要禁用沙箱或批准/白名单脚本才能使用此方法,因为否则StreamingTemplateEngine的某些内部组件将被阻止。

流模板引擎的模板格式如下:${variable}$VARIABLE形式的任何内容都将被直接替换,并且<% %>/<%= %>语法也可以用于嵌入scriptlet(例如循环或if语句)(类似于ERB模板) 。 StreamingTemplateEngine的文档可用here

关于templates - Jenkins管道: templating a file with variables,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39147966/

10-11 22:25
查看更多