Kubernetes 快速替換 Job



前言

  • 在 CI/CD 時,如果不是用 helm hook 自動處理 job 的話,手動更新然後下上通常都有點麻煩。
  • 這篇紀錄用 jq 快速置換 job 的方式。



用 jq 替換 job

單純下上

主要先把 metadata.* 以及 status 部分刪掉,然後再重新 apply。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
replace_job () {
    local _ns _job_name
    _ns=$1
    _job_name=$2
    tmp_file=$(mktemp)
    kubectl -n "${_ns}" get job "${_job_name}" -ojson \
    | jq 'del(.status, .metadata.creationTimestamp, .metadata.generation, .metadata.resourceVersion, .metadata.uid, .metadata.annotations, .metadata.labels, .spec.selector, .spec.template.metadata )' \
    > "${tmp_file}"
    kubectl delete -n "${_ns}" job "${_job_name}"
    kubectl apply -f "${tmp_file}"
    rm -f "${tmp_file}"
}

之後就可以用這個 function 下上 job 了。

1
replace_job my_namespace my_job_name


下上、且替換 image

如果需要替換 image 的話,跟上面類似,但是要替換 tag

(要先更新好 YOUR_IMAGE_REGISTRY 這個變數)

像這樣:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
replace_job () {
    local _ns _job_name _image_tag
    _ns=$1
    _job_name=$2
    _image_tag=$3
    tmp_file=$(mktemp)
    kubectl -n "${_ns}" get job "${_job_name}" -ojson \
    | jq --arg image_tag ${YOUR_IMAGE_REGISTRY}:"${_image_tag}" 'del(.status, .metadata.creationTimestamp, .metadata.generation, .metadata.resourceVersion, .metadata.uid, .metadata.annotations, .metadata.labels, .spec.selector, .spec.template.metadata )
        | .spec.template.spec.containers[0].image |= $image_tag' \
    > "${tmp_file}"

    kubectl delete -n "${_ns}" job "${_job_name}"
    kubectl apply -f "${tmp_file}"
    rm -f "${tmp_file}"
}

Note

  • 因為 image_tag 的錢號 $ 會被 jq 誤認,所以要用 --arg 來傳遞變數 [1]。

同樣方式:

1
2
3
4
5
replace_job my_namespace my_job_name my_image_tag

# YOUR_IMAGE_REGISTRY 要先設定好
# e.g.
# YOUR_IMAGE_REGISTRY=ktlast/my-best-api replace_job my_namespace my_job_name my_image_tag

如果 YOUR_IMAGE_REGISTRY 時常更動的話,也可以把它抽出當成變數。




REF

  1. https://stackoverflow.com/a/34747439/5430476
Licensed under CC BY-NC-SA 4.0
最後更新 2024-09-30 02:27

主題 StackJimmy 設計