使用Jenkins管道在电子邮件ext模板中访问变量

时间:2018-04-17 18:16:54

标签: jenkins jenkins-plugins jenkins-pipeline email-ext jenkins-email-ext

我正在尝试使用Jenkins管道附加模板文件, emailext 。 模板文件中无法访问变量(PROJNAME),我收到例外电子邮件:

  

模板渲染期间引发异常:没有这样的属性:类的env:SimpleTemplateScript21 groovy.lang.MissingPropertyException:没有这样的属性:类的env:org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap中的SimpleTemplateScript21(ScriptBytecodeAdapter.java: 53)在org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)at SimpleTemplateScript21.run(SimpleTemplateScript21) .groovy:1)at groovy.text.SimpleTemplateEngine $ SimpleTemplate $ 1.writeTo(SimpleTemplateEngine.java:168)at groovy.text.SimpleTemplateEngine $ SimpleTemplate $ 1.toString(SimpleTemplateEngine.java:180)at hudson.plugins.emailext.plugins。 org.jenkinsci.plugins.tokenmacro.DataBoundTokenMacro.evaluate(D)中的hudson.plugins.emailext.plugins.content.ScriptContent.evaluate(ScriptContent.java:82)中的content.ScriptContent.renderTemplate(ScriptContent.java:151) ataBoundTokenMacro.java:208)org.jenkinsci.plugins.tokenmacro.Parser.processToken(Parser.java:308)org.jenkinsci.plugins.tokenmacro.Action $ KiHW1UeqOdqAwZul.run(未知来源)org.parboiled.matchers。 ActionMatcher.match(ActionMatcher.java:96)位于org.parboiled.MatcherContext.runMatcher(MatcherContext.java:351)的org.parboiled.parserunners.BasicParseRunner.match(BasicParseRunner.java:77)

管道脚本:

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}"
}

模板(filename - 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”)

3 个答案:

答案 0 :(得分:1)

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

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

然后您可以在html中使用本地变量项目,如

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

注意:您可以使用envOverrides

使用所有必需的env变量

答案 1 :(得分:1)

唯一适合我的电子邮件模板:

<%
    import hudson.model.*

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

然后你可以使用

${YOUR_VARIABLE}

答案 2 :(得分:0)

要完成Pakeer的回答,如果需要在电子邮件模板中使用复杂数据,则可以使用json序列化数据并将其通过env vars传递。 我的需要是从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>