使用 Jenkins 管道访问电子邮件分机模板中的变量

Access variable in email ext template using Jenkins pipeline

我正在尝试使用 Jenkins 管道 emailext 附加模板文件。 变量 (PROJNAME) 在模板文件中不可访问,我收到异常邮件:

Exception raised during template rendering: No such property: env for class: SimpleTemplateScript21 groovy.lang.MissingPropertyException: No such property: env for class: SimpleTemplateScript21 at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53) at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307) at SimpleTemplateScript21.run(SimpleTemplateScript21.groovy:1) at groovy.text.SimpleTemplateEngine$SimpleTemplate.writeTo(SimpleTemplateEngine.java:168) at groovy.text.SimpleTemplateEngine$SimpleTemplate.toString(SimpleTemplateEngine.java:180) at hudson.plugins.emailext.plugins.content.ScriptContent.renderTemplate(ScriptContent.java:151) at hudson.plugins.emailext.plugins.content.ScriptContent.evaluate(ScriptContent.java:82) at org.jenkinsci.plugins.tokenmacro.DataBoundTokenMacro.evaluate(DataBoundTokenMacro.java:208) at org.jenkinsci.plugins.tokenmacro.Parser.processToken(Parser.java:308) at org.jenkinsci.plugins.tokenmacro.Action$KiHW1UeqOdqAwZul.run(Unknown Source) at org.parboiled.matchers.ActionMatcher.match(ActionMatcher.java:96) at org.parboiled.parserunners.BasicParseRunner.match(BasicParseRunner.java:77) at org.parboiled.MatcherContext.runMatcher(MatcherContext.java:351)

管道脚本:

stage('Email') {
    def mailRecipients = "myemail@abc.com"
    def jobStatus = currentBuild.currentResult
    env.PROJNAME = 'project_name'
    echo "projname is ${PROJNAME}"
emailext body: '''${SCRIPT, template="test.template"}''',
    mimeType: 'text/html',
    subject: "[Jenkins] ${jobStatus}",
    to: "${mailRecipients}"
}

模板(文件名 - test.template):

<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>Job is '${env.PROJNAME}'</p>
</body>
</html>

还尝试将模板文件中的变量语法替换为“${PROJNAME}”和“${ENV, var="PROJNAME"} " 但没有运气。有什么建议吗?

当我在模板文件中替换为 ENV(var="PROJNAME") 时没有帮助。我收到的电子邮件为:

这是一个标题

作业是 ENV(var="PROJNAME")

尝试覆盖 html 模板中的 env 变量,如下所示

<%
def envOverrides = it.getAction("org.jenkinsci.plugins.workflow.cps.EnvActionImpl").getOverriddenEnvironment()
    project =  envOverrides["PROJNAME"]
%>

然后您可以在 html 中使用局部变量 project,例如

<p> Job is ${project} </p>

注意:您可以使用 envOverrides

使用所有必需的环境变量

电子邮件模板中唯一对我有用的:

<%
    import hudson.model.*

    def YOUR_VARIABLE= build.getEnvVars()["SOME_BUILD_PARAMETER"];
%>

那你就可以使用

${YOUR_VARIABLE}

要完成 Pakeer 的回答,如果您需要在电子邮件模板中使用复杂数据,您可以使用 json 序列化数据并通过环境变量传递。 我需要从 jira 查询一些数据,然后将其发送到自定义电子邮件模板中,最后我得到了这个 jenkins 管道:

payload = [
    jql: "project = WFMA and issuetype in (Incident, Bug) and fixVersion = \"${version}\"",
    startAt: 0,
    maxResults: maxResults,
    fields: [ "id", "issuetype", "summary", "priority", "status", "assignee" ]
]

response = httpRequest(url: jiraRestBaseUrl + "search",
    acceptType: 'APPLICATION_JSON', contentType: 'APPLICATION_JSON', 
    httpMode: 'POST', validResponseCodes: '100:599', requestBody: new JsonBuilder(payload).toString(), 
    authentication: 'jira-wsf-jenkins', timeout: 30)

if (response.status != 200) {
    echo("JIRA REST API returned an error ${response.status} when searching for issues, content is ${response.content}")
    throw new hudson.AbortException(("JIRA REST API returned an error ${response.status}"))
}

jsonResponse = new JsonSlurper().parseText(response.content)
if (jsonResponse.total > jsonResponse.maxResults) {
    throw new hudson.AbortException(("total is bigger than maxResults, please implements pagination"))
}

if (jsonResponse.total == 0) {
    echo('No issue associated with this release, skipping')
} 
else {
    def emailSubject = "Please verify the ticket statuses for the release ${version} deployed on ${plannedUatDate}"
    def releaseIssues = jsonResponse.issues
    env.release_name = version
    env.release_date = plannedUatDate
    env.release_issues = JsonOutput.toJson(releaseIssues)

    emailext(subject: emailSubject, body: '${SCRIPT, template="release-notes.template"}', to: emailRecipients)
}

还有这个电子邮件模板:

<STYLE>
BODY, TABLE, TD, TH, P {
    font-family: Calibri, Verdana, Helvetica, sans serif;
    font-size: 14px;
    color: black;
}
.section {
    width: 100%;
    border: thin black dotted;
}
.td-title {
    background-color: #666666;
    color: white;
    font-size: 120%;
    font-weight: bold;
    padding-left: 5px;
}
.td-header {
    background-color: #888888;
    color: white;
    font-weight: bold;
    padding-left: 5px;
}
</STYLE>

<BODY>

<!-- Release TEMPLATE -->

<%
import groovy.json.JsonSlurper

def envOverrides = it.getAction("org.jenkinsci.plugins.workflow.cps.EnvActionImpl").getOverriddenEnvironment()
release_name =  envOverrides["release_name"]
release_date =  envOverrides["release_date"]
release_issues = new JsonSlurper().parseText(envOverrides["release_issues"])
%>

Dear team member,<br/>
<br/>
The release ${release_name} is about to be deployed on the ${release_date} on Master UAT. <br/>
You will find below the list of tickets included in the release. Please have a look and make the necessary updates so the status 
is aligned with our guidelines.<br/>
<br/>

<table class="section">
    <tr class="tr-title">
    <td class="td-title" colspan="6">Issues associated with the release</td>
    </tr>
    <tr>
        <td class="td-header">Issue Key</td>
        <td class="td-header">Issue Type</td>
        <td class="td-header">Priority</td>
        <td class="td-header">Status</td>
        <td class="td-header">Summary</td>
        <td class="td-header">Assignee</td>
    </tr>
    <% release_issues.each {
    issue -> %>
    <tr>
    <td><a href="https://jira.baseurl.com/browse/${issue.key}">${issue.key}</a></td>
    <td>${issue.fields.issuetype?.name.trim()}</td>
    <td>${issue.fields.priority?.name}</td>
    <td>${issue.fields.status?.name}</td>
    <td>${issue.fields.summary}</td>
    <td>${issue.fields.assignee?.name}</td>
    </tr>
    <% } %>
</table>
<br/>

</BODY>

Pakeer 的回答对我也有用。我只是想指出我必须在管道脚本中设置我的环境变量

...
steps {
 script {
  env.MY_VARIABLE="Some value"
 }
}

我的管道脚本的环境 {} 块中的定义无效。

@Jinlxz 刘: 据我了解是对ScriptContentBuildWrapper的引用: https://javadoc.jenkins.io/plugin/email-ext/hudson/plugins/emailext/plugins/content/ScriptContentBuildWrapper.html