我有一本需要根据操作系统运行的剧本。 UseCase:假设有一个正在运行的服务。
在Linux上,我们可以使用以下命令检查它是否已安装并正在运行 systemctl状态application.service
在Windows上执行命令时,我们将使用 sc查询“ ServiceName” |找到“正在运行”
现在我们必须根据上述输出安装命令,这需要我们根据操作系统隔离剧本。
经典示例:基于操作系统创建目录
- name: Install QCA Agent on Linux targets
hosts: all
gather_facts: true
remote_user: root
tasks:
- name: Create Directory for Downloading Qualys Cloud Agent
sudo: yes
sudo_user: root
file:
path: /usr/q1/
state: directory
owner: root
group: root
mode: 0777
recurse: no
- name: Create Directory for Downloading Qualys Cloud Agent
win_file:
path: c:\q1
state: directory
owner: Administrator
group: Administrator
mode: 0777
recurse: no
只有满足以下条件之一,即是Windows还是Unix OS,该剧本才会成功。我可以始终添加一个条件,该条件将根据以下条件提示:
when: ansible_distribution == 'Redhat' or ansible_distribution == 'CentOS'
但是我要达到的目标是基于触发我的playbook.yml文件的条件。
name: Load a variable file based on the OS type, or a default if not found. Using free-form to specify the file.
include_vars: "{{ item }}"
with_first_found:
- "{{ ansible_distribution }}.yaml"
- "{{ ansible_os_family }}.yaml"
- default.yaml
https://docs.ansible.com/ansible/2.5/modules/include_vars_module.html?highlight=with_first_found
我想知道是否有更好的示例来说明我可以实现的相同示例,或者是否有其他方法可以实现相同目标。
谢谢
答案 0 :(得分:1)
您从Ansible文档中显示的示例几乎是最佳实践,并且在处理多个操作系统的许多剧本(以及相关角色)中很常见。如果您使用的代码不同(而不是此处的变量示例),则将使用include_tasks
而不是include_vars
,但是概念是相同的。