带有变量的 Ansible 条件

问题描述 投票:0回答:1

我必须构建一个集群,其中某些软件包应安装在所有主机上,而其他软件包仅安装在特定主机上。

我希望向 yum 安装循环添加一个条件,以根据我的清单组(主、从、全部)选择目标主机。

- name: Install Package
  when: inventory_hostname in groups[ {{item.host }} ]
  yum:
    name: "{{ item.name }}"
    state: present
  loop:
    - {name: 'package_1', host: 'master'}
    - {name: 'package_2', host: 'slave'}
    - {name: 'package_3', host: 'all'}

我知道 jinja2 模板不是一个选项,但我找不到正确的方法。谢谢!

loops ansible conditional-statements
1个回答
0
投票

问:“我找不到正确的方法。

你就快到了。一种可能的方法如下所示。

有关包含内容的库存示例

[cluster:children]
primary
secondary

[primary]
one.example.com
two.example.com

[secondary]
three.example.com
four.example.com
ansible-inventory --graph
@all:
  |--@ungrouped:
  |--@cluster:
  |  |--@primary:
  |  |  |--one.example.com
  |  |  |--two.example.com
  |  |--@secondary:
  |  |  |--three.example.com
  |  |  |--four.example.com

一个最小的示例手册

---
- hosts: cluster
  become: false
  gather_facts: false

  tasks:

  - name: Install Package
    debug:
      msg: "Install: {{ item.name }}"
    when: item.host in group_names
    loop:
      - {name: 'package_1', host: 'primary'}
      - {name: 'package_2', host: 'secondary'}
      - {name: 'package_3', host: 'cluster'}
    loop_control:
      label: "{{ item.name }}"

将产生

的输出
TASK [Install Package] ***********************
ok: [one.example.com] => (item=package_1) =>
  msg: 'Install: package_1'
ok: [one.example.com] => (item=package_3) =>
  msg: 'Install: package_3'
ok: [two.example.com] => (item=package_1) =>
  msg: 'Install: package_1'
ok: [two.example.com] => (item=package_3) =>
  msg: 'Install: package_3'
ok: [three.example.com] => (item=package_2) =>
  msg: 'Install: package_2'
ok: [three.example.com] => (item=package_3) =>
  msg: 'Install: package_3'
ok: [four.example.com] => (item=package_2) =>
  msg: 'Install: package_2'
ok: [four.example.com] => (item=package_3) =>
  msg: 'Install: package_3'
© www.soinside.com 2019 - 2024. All rights reserved.