GitLab Pipeline多行命令执行报错排查及修正请求
问题修复方案
错误原因
你用的YAML折叠标量>会把多行脚本的换行处理成空格,导致shell解析while循环和case语句时语法错乱,触发unexpected token 'done'错误。
修正后的YAML配置
把原来的>换成|-(保留所有换行的块标量),确保shell脚本的结构完整保留:
script: - . ./build-metadata - sh /create-aws-profile.sh - |- REGION="us-east-1" while : do ami_state=$(aws ec2 describe-images --region "$REGION" --image-ids "$US_EAST_AMI" | jq -r '.Images[].State') case "$ami_state" in available) echo "Now the AMI is available in the $REGION region" break ;; failed) echo "AMI is failed in $REGION region" break ;; pending) echo "AMI is still pending in $REGION region" ;; *) echo "AMI is in the unhandled state: $ami_state" break ;; esac sleep 10 done - aws ec2 modify-image-attribute --region us-east-1 --image-id "$US_EAST_AMI_ID" --attribute launchPermission --operation-type add --organizational-unit-arns "$OU"
额外优化点
- 给
jq表达式加上单引号:.Images[].State改成'.Images[].State',避免特殊字符解析异常; - 给所有变量引用(如
$ami_state、$US_EAST_AMI_ID)加上双引号,防止变量值含空格时出现参数拆分错误; - 统一case分支里
;;的缩进,保持语法规范。
更稳妥的替代方案
把循环逻辑写成单独的脚本文件(比如wait-for-ami.sh),再在CI脚本中调用,彻底规避YAML解析带来的问题:
script: - . ./build-metadata - sh /create-aws-profile.sh - chmod +x ./wait-for-ami.sh - ./wait-for-ami.sh - aws ec2 modify-image-attribute --region us-east-1 --image-id "$US_EAST_AMI_ID" --attribute launchPermission --operation-type add --organizational-unit-arns "$OU"
wait-for-ami.sh内容:
#!/bin/bash REGION="us-east-1" while : do ami_state=$(aws ec2 describe-images --region "$REGION" --image-ids "$US_EAST_AMI" | jq -r '.Images[].State') case "$ami_state" in available) echo "Now the AMI is available in the $REGION region" break ;; failed) echo "AMI is failed in $REGION region" break ;; pending) echo "AMI is still pending in $REGION region" ;; *) echo "AMI is in the unhandled state: $ami_state" break ;; esac sleep 10 done
内容的提问来源于stack exchange,提问作者Ravichandran
相关产品推荐
相关产品推荐

