You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins Groovy中转义JSON内容用于CloudFormation SSM参数

解决方案:Jenkins Groovy转义JSON并传递给CloudFormation

1. CloudFormation模板配置

先确认你的CFT中已定义SSM参数资源,参数类型设为String(转义后的JSON将以字符串形式传递):

Resources:
  AppConfigSSMParam:
    Type: AWS::SSM::Parameter
    Properties:
      Name: /my-app/config
      Type: String
      Value: !Ref EscapedJsonContent
      Description: JSON配置转义后存储为SSM字符串参数

Parameters:
  EscapedJsonContent:
    Type: String
    Description: 经Jenkins转义后的JSON内容

2. Jenkins Groovy转义JSON核心代码

在Jenkins流水线中读取Git拉取的JSON文件,针对性转义特殊字符,确保能被CloudFormation正确解析:

// 读取本地JSON文件内容
def rawJson = readFile(file: 'app-config.json')

// 转义JSON保留字符:反斜杠、双引号,按需处理换行/回车
def escapedJson = rawJson
  .replace('\\', '\\\\')  // 转义反斜杠(需转两次)
  .replace('"', '\\"')    // 转义双引号
  .replace('\n', '\\n')   // 转义换行符(可选,保留格式时用)
  .replace('\r', '\\r')   // 转义回车符

// 调用AWS CLI部署CloudFormation,传递转义后的参数
sh """
aws cloudformation deploy \
  --stack-name app-config-stack \
  --template-file ./cfn-template.yaml \
  --parameter-overrides EscapedJsonContent="${escapedJson}"
"""

3. 转义效果示例

原始JSON内容:

{
  "api": {
    "url": "https://api.example.com",
    "secret": "a\\b\"c"
  }
}

转义后的字符串:

"{\"api\":{\"url\":\"https://api.example.com\",\"secret\":\"a\\\\b\\\"c\"}}"

4. 简化转义技巧

可以直接用Groovy内置的JsonOutput工具类自动处理转义,更简洁可靠:

import groovy.json.JsonOutput

def rawJson = readFile(file: 'app-config.json')
def escapedJson = JsonOutput.toJson(rawJson)

内容的提问来源于stack exchange,提问作者Khalid Waseem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 06:43:15