Module 預設值 - module defaults

前一陣子在撰寫 playbook 操作 OpenShift 時,常常模組是同一個,裏面的 kubeconfig 是固定的,寫起來就很重複。 在以前不知道有 module_defaults 的時候,都是用變數來處理。現在知道有 module_defaults 以後,就可以用這個語法來處理了。

讓我們先看看沒有用 module_defaults 之前的用法:

---
- name: OpenShift example
  hosts: localhost

  tasks:
    - name: Create project
      community.okd.k8s:
        kubeconfig: "/etc/kubeconfig"
        state: present
        definition:
          kind: Project
          apiVersion: project.openshift.io/v1
          metadata:
            name: "Example"
            annotations:
              openshift.io/display-name: "Example"
          spec:
            finalizers:
              - kubernetes

    - name: Import image into image stream
      community.okd.k8s:
        kubeconfig: "/etc/kubeconfig"
        state: present
        definition:
          kind: ImageStream
          apiVersion: project.openshift.io/v1
          metadata:
            name: "hello-nginx"
            namespace: "Example"
          spec:
            lookupPolicy:
              local: false
            tags:
              - name: "1.0.0"
                from:
                  kind: DockerImage
                  name: "quay.io/redhattraining/hello-nginx"
                generation: 1
                referencePolicy
                  type: Source

這個時候,就可以利用 module_defaults,那麼 playbook 就可以改寫為

---
- name: OpenShift example
  hosts: localhost

  module_defaults:
    community.okd.k8s:
      kubeconfig: "/etc/kubeconfig"

  tasks:
    - name: Create project
      community.okd.k8s:
        state: present
        definition:
          kind: Project
          apiVersion: project.openshift.io/v1
          metadata:
            name: "Example"
            annotations:
              openshift.io/display-name: "Example"
          spec:
            finalizers:
              - kubernetes

    - name: Import image into image stream
      community.okd.k8s:
        state: present
        definition:
          kind: ImageStream
          apiVersion: project.openshift.io/v1
          metadata:
            name: "hello-nginx"
            namespace: "Example"
          spec:
            lookupPolicy:
              local: false
            tags:
              - name: "1.0.0"
                from:
                  kind: DockerImage
                  name: "quay.io/redhattraining/hello-nginx"
                generation: 1
                referencePolicy
                  type: Source

這樣就可以把共用的 kubeconfig 都寫在 module_defaults 裡,日後調整會比較容易。

參考資料:Module defaults — Ansible Documentation