5.4.3.2. 在本地测试 k8s Ansible 模块
有时,开发人员最好在其本地机器上运行 Ansible 代码,而不必每次都运行和重构 Operator。
流程
安装
community.kubernetes集合:$ ansible-galaxy collection install community.kubernetes初始化基于 Ansible 的新 Operator 项目:
$ operator-sdk new --type ansible \ --kind Test1 \ --api-version test1.example.com/v1alpha1 test1-operator输出示例
Create test1-operator/tmp/init/galaxy-init.sh Create test1-operator/tmp/build/Dockerfile Create test1-operator/tmp/build/test-framework/Dockerfile Create test1-operator/tmp/build/go-test.sh Rendering Ansible Galaxy role [test1-operator/roles/test1]... Cleaning up test1-operator/tmp/init Create test1-operator/watches.yaml Create test1-operator/deploy/rbac.yaml Create test1-operator/deploy/crd.yaml Create test1-operator/deploy/cr.yaml Create test1-operator/deploy/operator.yaml Run git init ... Initialized empty Git repository in /home/user/go/src/github.com/user/opsdk/test1-operator/.git/ Run git init done$ cd test1-operator使用您想要的 Ansible 逻辑来修改
roles/test1/tasks/main.yml文件。本示例通过变量切换来创建和删除命名空间。- name: set test namespace to "{{ state }}" community.kubernetes.k8s: api_version: v1 kind: Namespace state: "{{ state }}" name: test ignore_errors: true1 - 1
- 设置
ignore_errors: true可确保删除不存在的项目不会失败。
修改
roles/test1/defaults/main.yml文件,将默认state设置为present:state: present在顶层目录中创建一个 Ansible
playbook playbook.yml文件,其中包含test1角色:- hosts: localhost roles: - test1运行 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 [test1 : set test namespace to present] changed: [localhost] PLAY RECAP ********************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0检查是否已创建命名空间:
$ oc get namespace输出示例
NAME STATUS AGE default Active 28d kube-public Active 28d kube-system Active 28d test Active 3s重新运行 playbook,设置
state为absent:$ 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 [test1 : set test namespace to absent] changed: [localhost] PLAY RECAP ********************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0检查是否已删除命名空间:
$ oc get namespace输出示例
NAME STATUS AGE default Active 28d kube-public Active 28d kube-system Active 28d