【发布时间】:2022-10-01 16:38:36
【问题描述】:
我正在使用 Ansible 并熟悉剧本中的任务控制。我正在为fail 模块和fail_when 声明而苦苦挣扎。这是我从事的一个实验室,它似乎可以工作,但我想看看如何使用 fail 模块或 fail_when 来处理,如果需要的话。
这是我努力完成的任务:
- 仅当当前操作系统为 CentOS 或 RHEL 8 或更高版本时才安装软件包。如果不是这种情况,playbook 应该会失败并显示错误消息“主机
hostname不符合最低要求”,其中主机名替换为当前主机名。
这是我的问题:
- 在
fail模块中使用ansible_facts似乎不能很好地锻炼 - 我不明白如何在此任务中使用
fail_when这是我的解决方案:
--- - name: Install packages hosts: all vars_files: vars/pack.yml tasks: - name: Install packages block: - name: Install packages and loop yum: name: \"{{ item.package }}\" state: \"{{ item.state }}\" loop: \"{{ packages }}\" when: ( ansible_facts[\'distribution\'] == \"CentOS\" and ansible_facts[\'distribution_version\'] == \"8\" ) or ( ansible_facts[\'distribution\'] == \"RedHat\" and ansible_facts[\'distribution_version\'] >= \"8.1\" ) - name: Copy file to /tmp copy: content: \"Welcome to my webserver\" dest: /tmp/index.html notify: restart web - name: Check for firewalld yum: name: firewalld state: latest - name: verify firewalld is started service: name: firewalld state: started - name: open firewall ports for http and https firewalld: service: \"{{ item.service }}\" state: \"{{ item.state }}\" immediate: yes permanent: yes loop: \"{{ firewall }}\" rescue: - name: fail if any task fail fail: msg: did not meet the requirements handlers: - name: restart web service: name: httpd state: restarted顺便说一句,我正在使用 Sander Van Vugt 的 RHCE 考试书。这是实验室 7-1。他的 Github 在实验室上有点欠缺。
这是更好的优化剧本:
--- - name: End of chapter lab 7 final hosts: all become: true vars_files: - vars/pack.yml tasks: - name: Install httpd and mod_ssl packages yum: name: \"{{ item.package }}\" state: \"{{ item.state }}\" loop: \"{{ packages }}\" when: ( ansible_facts[\'distribution\'] == \"CentOS\" and ansible_facts[\'distribution_version\'] <= \"8\" ) or ( ansible_facts[\'distribution\'] == \"RedHat\" and ansible_facts[\'distribution_version\'] <= \"8\" ) - name: Fail if the following is not met fail: msg: \"Host {{ ansible_facts[\'hostname\'] }} does not meet the minimal requirements\" when: not (( ansible_facts[\'distribution\'] == \"CentOS\" and ansible_facts[\'distribution_version\'] <= \"8\" ) or ( ansible_facts[\'distribution\'] == \"RedHat\" and ansible_facts[\'distribution_version\'] <= \"8\" )) - name: Copy tmp file copy: content: \"Welcome to my webserver\" dest: /tmp/index.html - name: Configure Firewalld for http and https rules firewalld: service: \"{{ item.service }}\" state: \"{{ item.state }}\" immediate: yes permanent: yes loop: \"{{ firewall }}\"
标签: ansible