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

标签 ansible ansible-inventory ansible-facts

我有一个名为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/

相关文章:

amazon-web-services - 如何在 Amazon Linux EC2 中安装 Ansible?

ansible - 如何在ansible playbook中只运行一项任务?

ansible - 'dict object' 在 Ansible Playbook 中没有属性 'stdout'

Ansible:如何在 Ansible 中仅从 FQDN 获取 IP 地址?

ansible - 遍历 Ansible 中的两个列表

ansible - 运行时在控制台上打印命令 stdout

python - Ansible python 版本不会改变

amazon-web-services - Ansible 动态 list : Authentication error retrieving ec2 inventory

Ansible,如何在主机 list 中定义列表?

ansible - 在动态 list 脚本中访问 group_vars/all