我有一个kubernetes入口清单YAML,如下所示:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
certmanager.k8s.io/acme-http01-edit-in-place: "true"
certmanager.k8s.io/cluster-issuer: letsencrypt
name: staging
namespace: dev
spec:
rules:
- host: staging.domain.com
http:
paths:
- backend:
serviceName: task-11111
servicePort: 80
path: /task-11111/*
- backend:
serviceName: task-22222
servicePort: 80
path: /task-22222/*
- backend:
serviceName: task-33333
servicePort: 80
path: /task-33333/*
tls:
- hosts:
- staging.domain.com
secretName: staging-domain-com
我要实现的目的是添加(如果不存在)或删除(如果存在)后端块。我现在所拥有的:
yq -y '.spec.rules[].http.paths += [{ "backend": { "serviceName": "'${CI_COMMIT_REF_NAME}'", "servicePort": 80}, "path": "/'${CI_COMMIT_REF_NAME}'/*"}]'
(添加一个具有可变值的新块,但是如果它已经存在就不会打扰)
yq -y 'del(.. | .paths? // empty | .[] | select(.path |contains("'${CI_COMMIT_REF_NAME}'")) )'
(与jq: error (at <stdin>:0): Invalid path expression with result {"backend":{"serviceName":...
失败)
因此规则在删除后可能看起来像这样(假设CI_COMMIT_REF_NAME
= task-33333
):
spec:
rules:
- host: staging.domain.com
http:
paths:
- backend:
serviceName: task-11111
servicePort: 80
path: /task-11111/*
- backend:
serviceName: task-22222
servicePort: 80
path: /task-22222/*
或添加后类似(假设CI_COMMIT_REF_NAME
= task-44444
):
spec:
rules:
- host: staging.domain.com
http:
paths:
- backend:
serviceName: task-11111
servicePort: 80
path: /task-11111/*
- backend:
serviceName: task-22222
servicePort: 80
path: /task-22222/*
- backend:
serviceName: task-33333
servicePort: 80
path: /task-33333/*
- backend:
serviceName: task-44444
servicePort: 80
path: /task-44444/*
任何帮助将不胜感激。
答案 0 :(得分:2)
[对以下内容进行了修改,以反映对该问题的更新。]
假设CI_COMMIT_REF_NAME以$ CI_COMMIT_REF_NAME的身份提供给jq,可以使用jq和以下命令行参数来完成此操作:
--arg CI_COMMIT_REF_NAME "$CI_COMMIT_REF_NAME"
适当的jq过滤器将遵循以下几行:
.spec.rules[0].http.paths |=
(map(select(.path | index($CI_COMMIT_REF_NAME) | not)) as $new
| if ($new | length) == length
then . + [{ "backend": { "serviceName": $CI_COMMIT_REF_NAME, "servicePort": 80}, "path": ($CI_COMMIT_REF_NAME + "/*") }]
else $new
end )
您可以通过以下jq调用进行测试:
jq --arg CI_COMMIT_REF_NAME task-4444 -f program.jq input.json
当然input.json
是您的YAML的JSON版本。
(如果可能,我会优先使用index
而不是contains
。)