0

我正在尝试将 Kubespray 的所有角色包装在块/救援块中,所以我不得不从通常的roles包含中移动,如下所示:

- hosts: kube-master[0]
  any_errors_fatal: "{{ any_errors_fatal | default(true) }}"
  roles:
    - { role: kubespray-defaults}
    - { role: kubernetes-apps/rotate_tokens, tags: rotate_tokens, when: "secret_changed|default(false)" }
    - { role: win_nodes/kubernetes_patch, tags: ["master", "win_nodes"]}

对此:

- hosts: kube-master[0]
  any_errors_fatal: "{{ any_errors_fatal | default(true) }}"
  vars:
    roles:
      - name: "kubespray-defaults"
      - name: kubernetes-apps/rotate_tokens
        tags: rotate_tokens
        when: "secret_changed|default(false)"
      - name: win_nodes/kubernetes_patch
        tags: ["master", "win_nodes"]
      - name: "ems-notification"
        msg: kubespray-defaults, kubernetes-apps/rotate_tokens and win_nodes/kubernetes_patch completed

  tasks:
  - include_tasks: roles/a4-roles/tasks/main.yml
    loop: "{{ roles }}"

a4-roles/tasks/main.yml 是:

- name: a4-roles
  when: item.when | default(omit)
  block:
    - include_role:
        name: "{{ item.name }}"
        apply:
          tags: >-
            {%- if item.tags is defined -%}
            "{{ item.tags }}"
            {%- else -%}
            ""
            {%- endif -%}
  rescue:
    - include_role:
        name: "ems-notification"
      vars:
        msg: an error has occurred
        host: "{{ inventory_hostname }}"
        result: "{{ ansible_failed_result.msg | trim | default(omit) }}"
        role: "{{ item.name }}"
        error: "true"

问题在于,kubespray-defaults以及其他角色正在设置roles块中后续角色正在使用的一些变量和默认值。使用include_role这些变量时,默认值会丢失。有什么办法可以保留它们并将它们传递给下一个角色?

4

1 回答 1

1

我找到了一种通过使用public指令来解决这个问题的方法。将其设置为true与以下所有角色共享默认值和变量。

我所要做的就是更改 a4-roles/tasks/main.yml 并使其如下所示:

- name: a4-roles
  when: item.when | default(omit)
  block:
    - include_role:
        name: "{{ item.name }}"
        public: true
        apply:
          tags: >-
            {%- if item.tags is defined -%}
            "{{ item.tags }}"
            {%- else -%}
            ""
            {%- endif -%}
  rescue:
    - include_role:
        name: "ems-notification"
      vars:
        msg: an error has occurred
        host: "{{ inventory_hostname }}"
        result: "{{ ansible_failed_result.msg | trim | default(omit) }}"
        role: "{{ item.name }}"
        error: "true"

这仍然在污染全局堆栈,因为这些默认值和变量正在与所有角色共享,而不仅仅是那些由我的循环处理的角色。在我写这篇文章的时候,我认为没有更好的解决方案。

于 2019-10-11T11:02:23.473 回答