AWS EventBridge Scheduler创建命令本地正常Jenkins执行报错求助
问题分析
报错源于Jenkins流水线的Shell环境中,--target参数的嵌套JSON转义处理错误。本地环境与Jenkins Shell执行环境的转义规则存在差异,导致传递给AWS CLI的JSON格式不合法,具体是Input字段内的嵌套JSON未正确转义,出现未闭合的引号。
解决方案
以下三种方法均可解决该问题:
方法1:使用Heredoc简化转义
通过临时文件传递JSON内容,彻底规避多层转义的混乱,可读性和稳定性更强:
pipeline { agent any stages { stage('Build') { steps { sh """ aws sts get-caller-identity cat << 'EOF' > target.json { "Arn": "arn:aws:scheduler:::aws-sdk:ec2:stopInstances", "RoleArn": "arn:aws:iam::966858xxxxx:role/service-role/Amazon_EventBridge_Invoke_Action_On_EC2_Instance_2111992150", "Input": "{\"InstanceIds\": [\"i-0ad766a46xxxxxx\"]}" } EOF aws scheduler create-schedule --name ${name} \ --schedule-expression "at(2022-11-01T11:00:00)" \ --flexible-time-window '{ "Mode": "OFF" }' \ --target file://target.json """ } } } }
方法2:修正嵌套JSON的转义层级
针对Jenkins Shell的转义规则,对Input字段内的嵌套JSON增加一层转义,确保AWS CLI收到合法的JSON:
pipeline { agent any stages { stage('Build') { steps { sh """ aws sts get-caller-identity aws scheduler create-schedule --name ${name} \ --schedule-expression "at(2022-11-01T11:00:00)" \ --flexible-time-window '{ "Mode": "OFF" }' \ --target '{\"Arn\": \"arn:aws:scheduler:::aws-sdk:ec2:stopInstances\", \"RoleArn\": \"arn:aws:iam::966858xxxxx:role/service-role/Amazon_EventBridge_Invoke_Action_On_EC2_Instance_2111992150\", \"Input\": \"{\\\\\\\"InstanceIds\\\\\\\": [\\\\\\\"i-0ad766a46xxxxxx\\\\\\\"]}\"}' """ } } } }
方法3:用单引号包裹整个target参数
利用Shell中单引号不解析转义字符的特性,调整参数包裹方式,减少转义层级:
pipeline { agent any stages { stage('Build') { steps { sh """ aws sts get-caller-identity aws scheduler create-schedule --name ${name} \ --schedule-expression "at(2022-11-01T11:00:00)" \ --flexible-time-window '{ "Mode": "OFF" }' \ --target '{\"Arn\": \"arn:aws:scheduler:::aws-sdk:ec2:stopInstances\", \"RoleArn\": \"arn:aws:iam::966858xxxxx:role/service-role/Amazon_EventBridge_Invoke_Action_On_EC2_Instance_2111992150\", \"Input\": \"{\\\"InstanceIds\\\": [\\\"i-0ad766a46xxxxxx\\\"]}\"}' """ } } } }
内容的提问来源于stack exchange,提问作者Sudip Pramanick
相关产品推荐
相关产品推荐

