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

如何通过Bash脚本调整Kubernetes RoleBinding YAML输出的末尾格式

方案1:更稳妥的Here Document实现(推荐)

使用Bash的Here Document语法生成YAML,完全不需要手动处理转义字符,格式和你期望的最终输出完全对齐,不会出现缩进、空格异常问题:

# 提前定义你的变量即可
rolebindingname="monitoring-gitlab-rolebinding"
namespace="mdep"
accountname="monitoring-gitlab"

# 直接按目标YAML格式写即可,变量会自动解析
kubectl apply -f - <<EOF
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: $rolebindingname
  namespace: $namespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin
subjects:
- kind: ServiceAccount
  name: $accountname
EOF

方案2:修复原有脚本

你原有脚本的问题出在echo -e $rolebinding没有给变量加双引号,Shell会对未加引号的变量做分词处理,把换行符、连续空格都替换成单个空格,导致YAML格式错乱,只需加双引号即可:

rolebinding="apiVersion: rbac.authorization.k8s.io/v1beta1\nkind: RoleBinding\nmetadata:\n  name: $rolebindingname\n  namespace: $namespace\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: ClusterRole\n  name: admin\nsubjects:\n- kind: ServiceAccount\n  name: $accountname"
echo -e "$rolebinding" | kubectl apply -f -

内容的提问来源于stack exchange,提问作者Yassen Fouad Anis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:36:01