Ansible - 提示确认 运行 任务并由多个主机共享事实

Ansible - prompt for a confirmation to run tasks and share the fact by multiple hosts

我有一本名为 delete.yml

的简单剧本
- hosts: all
  become: false
  tasks:
    - pause:
        prompt: "Are you sure you want to delete \" EVERYTHING \"? Please confirm with \"yes\". Abort with \"no\" or Ctrl+c and then \"a\""
      register: confirm_delete
    - set_fact:
        confirm_delete_fact: "{{ confirm_delete.user_input | bool }}"

- hosts: all
  become: false
  roles:
    - {role: destroy when: confirm_delete_fact }

我的库存是

[my_group]
192.168.10.10
192.168.10.11
192.168.10.12

所以我运行剧本

ansible-playbook delete.yml -i inventoryfile -l my_group

一切正常,但仅适用于一台主机,my_group 中的其他主机因条件检查而被跳过

怎么了?

你可以试试:

- hosts: all
  become: false
  tasks:
    - pause:
        prompt: "Are you sure you want to delete \" EVERYTHING \"? Please confirm with \"yes\". Abort with \"no\" or Ctrl+c and then \"a\""
      register: confirm_delete
    - name: Register dummy host with variable
      add_host:
        name: "DUMMY_HOST"
        confirm_delete_fact: "{{ confirm_delete.user_input | bool }}"

- hosts: all
  become: false
  vars:
    confirm_delete_fact: "{{ hostvars['DUMMY_HOST']['confirm_delete_fact'] }}"
  roles:
    - {role: destroy when: confirm_delete_fact }

如果您不想在 DUMMY_HOST 上出现错误(尝试连接 ssh),只需

- hosts: all,!DUMMY_HOST

解释:

如果你把你的提示放在任务中,它将被使用一次并且属于第一个主机的 hostvars,所以我创建一个新的虚拟主机并将变量传递给其他剧本。

你可以避免:

通过将提示放在任务上并测试变量 hostvars:

- hosts: all
  become: false
  vars_prompt:
  - name: confirm_delete
    prompt: "Are you sure you want to delete \" EVERYTHING \"? Please confirm with \"yes\". Abort with \"no\" or Ctrl+c and then \"a\""
    private: no
    default: no 
  tasks:
    - set_fact: 
        confirm_delete_fact: "{{ confirm_delete | bool }}"

- hosts: all
  become: false
  roles:
    - {role: destroy when: hostvars[inventory_hostname]['confirm_delete_fact'] }

您可以使用第二种解决方案,因为两个剧本中的主机相同。如果不同,我建议你使用第一种方案。