12.2.4.2. k8s Ansible モジュールのローカルでのテスト
開発者が毎回 Operator を実行し、再ビルドするのではなく、Ansible コードをローカルマシンから実行する方が利点がある場合があります。
手順
新規 Ansible ベースの Operator プロジェクトを初期化します。
$ operator-sdk new --type ansible --kind Foo --api-version foo.example.com/v1alpha1 foo-operator Create foo-operator/tmp/init/galaxy-init.sh Create foo-operator/tmp/build/Dockerfile Create foo-operator/tmp/build/test-framework/Dockerfile Create foo-operator/tmp/build/go-test.sh Rendering Ansible Galaxy role [foo-operator/roles/Foo]... Cleaning up foo-operator/tmp/init Create foo-operator/watches.yaml Create foo-operator/deploy/rbac.yaml Create foo-operator/deploy/crd.yaml Create foo-operator/deploy/cr.yaml Create foo-operator/deploy/operator.yaml Run git init ... Initialized empty Git repository in /home/dymurray/go/src/github.com/dymurray/opsdk/foo-operator/.git/ Run git init done
$ cd foo-operator
必要な Ansible ロジックを使用して
roles/foo/tasks/main.yml
ファイルを変更します。この例では、変数の切り替えと共に namespace を作成し、削除します。- name: set test namespace to {{ state }} k8s: api_version: v1 kind: Namespace state: "{{ state }}" name: test ignore_errors: true 1
- 1
ignore_errors: true
を設定することにより、存在しないプロジェクトを削除しても失敗しません。
roles/foo/defaults/main.yml
ファイルを、デフォルトでstate
をpresent
に設定するように変更します。state: present
上部ディレクトリーに、
Foo
ロールを含む Ansible Playbookplaybook.yml
を作成します。- hosts: localhost roles: - Foo
Playbook を実行します。
$ ansible-playbook playbook.yml [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] *************************************************************************** PROCEDURE [Gathering Facts] ********************************************************************* ok: [localhost] Task [Foo : set test namespace to present] changed: [localhost] PLAY RECAP ********************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0
namespace が作成されていることを確認します。
$ oc get namespace NAME STATUS AGE default Active 28d kube-public Active 28d kube-system Active 28d test Active 3s
state
をabsent
に設定して Playbook を再実行します。$ ansible-playbook playbook.yml --extra-vars state=absent [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] *************************************************************************** PROCEDURE [Gathering Facts] ********************************************************************* ok: [localhost] Task [Foo : set test namespace to absent] changed: [localhost] PLAY RECAP ********************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0
namespace が削除されていることを確認します。
$ oc get namespace NAME STATUS AGE default Active 28d kube-public Active 28d kube-system Active 28d