gpt4 book ai didi

templates - Jenkins 管道 : templating a file with variables

转载 作者:行者123 更新时间:2023-12-04 15:19:41 33 4
gpt4 key购买 nike

我有一个处理模板文件(例如 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将被直接替换和 <% %>/ <%= %>语法也可用于嵌入小脚本(例如循环或 if 语句)(类似于 ERB 模板)。 StreamingTemplateEngine 的文档有货 here .

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com