如何在Microsoft Teams通知Groovy脚本中使用Rundeck工作流全局变量
故障解决方法
1. 修正全局变量引用逻辑
Rundeck 2.10.8版本的通知插件execution对象不支持直接调用${execution.export.repo}获取export组变量,正确的取值路径为${execution.contextData.export.repo},同时建议添加空值判断避免变量不存在时导致JSON格式错误。
2. 修复curl命令转义问题
原脚本中直接拼接字符串构造JSON请求体,极易出现转义符冲突导致请求格式非法,触发Teams接口报错。建议改用Groovy内置JsonBuilder构造合法JSON后再发起请求,避免手动转义出错。
3. 前置校验逻辑
- 执行作业后查看执行详情的「变量」页,确认
export组下已生成repo变量且值正确,验证日志键值过滤器规则已生效 - 确认Rundeck运行用户对
/opt/rundeck-plugins/microsoftTeamsIncomingWebhook.groovy有读取权限 - 确认Rundeck服务器网络可正常访问配置的Teams Webhook地址,无防火墙、代理拦截
修正后的完整脚本
import com.dtolabs.rundeck.plugins.notification.NotificationPlugin; import groovy.json.JsonBuilder rundeckPlugin(NotificationPlugin){ title="Microsoft Teams Incoming Webhook" description="Customized webhook notification script" configuration{ webhook_url title:"MS Teams Incoming Webhook URL" } def ms_teams_notification = { // 先取repo变量,不存在则用默认值占位 def repoVal = execution.contextData?.export?.repo ?: "未获取到代码仓库信息" // 构造合法JSON def payload = new JsonBuilder([ title: execution.job.name, text: "[View job in Rundeck](${execution.href})\n\n\n\n**Status**: **${execution.status}**\n\n**Initiated by**: ${execution.user}\n\n**Repository**: ${repoVal}" ]).toString() // 执行curl命令,避免嵌套转义 def command = ['curl', '-X', 'POST', configuration.webhook_url, '-H', 'Content-Type: application/json', '-d', payload] def proc = command.execute() proc.waitForProcessOutput(System.out,System.err) return proc.exitValue()==0 } onsuccess ms_teams_notification onfailure ms_teams_notification }
内容的提问来源于stack exchange,提问作者markjeffridelacruz
相关产品推荐
相关产品推荐

