Ansible 中的循环、块和执行策略使用指南
1. Ansible 中的条件与循环基础
在 IT 运维任务中,我们常常需要创建复杂的条件。在 Ansible 里,变量默认不会被转换为特定类型,即便变量内容看起来像数字,Ansible 也会将其当作字符串处理。若要进行整数比较,需先将变量转换为整数类型。例如,以下代码展示了如何仅在 Fedora 35 及更高版本上运行任务:
tasks:
- name: Only perform this task on Fedora 35 and later
ansible.builtin.shell: echo "only on Fedora 35 and later"
when: ansible_facts['distribution'] == "Fedora" and ansible_facts['distribution_major_version']|int >= 35
除了条件逻辑,Ansible 还支持循环操作。当我们需要对一组数据执行单个任务时,循环能极大提高效率。比如,要在服务器上创建 15 个新用户组,使用循环可以避免编写 15 个单独的任务。
2. 循环的基本使用
首先,我们使用以下熟悉的清单文件:
[frontends]
web01.example.org https_port=8443
web02.example.org http_proxy=proxy.example.org
[frontends:
超级会员免费看
订阅专栏 解锁全文
21

被折叠的 条评论
为什么被折叠?



