如何在if else模式下执行ansible任务

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

我有以下代码,我想实现像 if-else 构造这样的条件逻辑:

- name: Download katello agent package
  get_url:
    url: "{{ abc_url }}/pub/yyy.rpm"
    dest: "{{ tmp_dir }}"

when rt in group_names url --> abc_url
rt not in group_names --> def_url

based on group_names, my URL changes.
ansible ansible-2.x
1个回答
1
投票

要内联插入条件逻辑:

- name: Download katello agent package
  get_url:
    url: "{{ 'abc_url' if 'rt' in group_names else 'def_url' }}/pub/yyy.rpm"
    dest: "{{ tmp_dir }}"

虽然这应该可行,但您可以使用 inventory 和 group_vars。 设置一个 ini 文件,例如库存.ini

[rt_group] rt_host ansible_host=your_rt_host

[other_group] other_host ansible_host=your_other_host

[全部:变量] abc_url=http://example.com/abc def_url=http://example.com/def tmp_dir=/path/to/destination

还有你的剧本(your_playbook.yml):

  • 名称:下载katello代理包主机:所有任务:
    • name:根据组设置URL 设置事实: 下载地址:“{{ abc_url }}” 当:“group_names 中的‘rt_group’”

    • name:根据组设置URL 设置事实: 下载地址:“{{ def_url }}” 当:“‘rt_group’不在 group_names 中”

    • 名称:下载包 获取网址: 网址:“{{ download_url }}/pub/yyy.rpm” 目标:“{{ tmp_dir }}”

© www.soinside.com 2019 - 2024. All rights reserved.