0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kyverno Chainsaw: 変数をシェルスクリプトに渡す方法

Last updated at Posted at 2025-05-09

Keyverno Chainsawでscriptに変数を渡す方法についての解説です。

Chainsawはテストケースごとにnamespaceをランダムで生成します。その名前は、applyなどであれば($namespace)変数でアクセスできます。しかし、scriptは直接アクセスできなので注意が必要です。

うまくいかない方法

安直にscript.content($namespace)を書いてもうまくいきません。content中の($namespace)は文字列展開されません。

apiVersion: chainsaw.kyverno.io/v1alpha1
kind: Test
metadata:
  name: my-test
spec:
  steps:
    - try:
        - script:
            content: |
              #!/bin/bash
              set -ux
              echo "Current namespace is ($namespace)"
#                                        ^^^^^^^^^^^^ これは展開されない

上の例だと、ただシェルで

echo "Current namespace is ($namespace)"

を実行しただけで、環境変数にnamespaceがないため次の出力結果のようにエラーになります。

    | 11:03:42 | my-test | step-1    | CMD       | RUN   |
        === COMMAND
        /nix/store/3z1jypscq2ld48kl089ywgwd8ri2rjxq-bash-5.2p37/bin/sh -c #!/bin/bash
        set -ux
        echo "Current namespace is ($namespace)"
    | 11:03:42 | my-test | step-1    | SCRIPT    | LOG   |
        === STDERR
        sh: line 3: namespace: unbound variable
    | 11:03:42 | my-test | step-1    | SCRIPT    | ERROR |
        === ERROR
        exit status 127

正しいやり方

変数をスクリプトに正しく渡すには、envを介在させます。例えば次のようにです。

apiVersion: chainsaw.kyverno.io/v1alpha1
kind: Test
metadata:
  name: my-test
spec:
  steps:
    - try:
        - script:
            env: # これを追加
              - name: NAMESPACE # 環境変数名
                value: ($namespace) # 値。ここは変数展開が効く。
            content: |
              #!/bin/bash
              set -ux
              echo "Current namespace is $NAMESPACE"
            #                            ^^^^^^^^^^ スクリプトとしては環境変数を参照する

このようにenvを追加し、Chainsawの変数をシェルの環境変数にマッピングしてあげる必要があります。

所感

ちょっと回りくどさはありますが、この方法でうまく動きます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?