我有一个名为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:
- 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'] }
您可以使用第二种解决方案,因为两个剧本中都有相同的主机。如果不同,我建议您使用第一种解决方案。
关于Ansible - 提示确认运行任务并由多个主机共享事实,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69976318/