【发布时间】:2021-07-01 15:30:39
【问题描述】:
嗨,我在下面试试。
task:
- name: Perform on primary server
blockinfile:
path: '/home/conf'
marker: "#-- {mark} Adding Values --"
block: |
{{ conf }}
when: "'host01' in inventory_hostname"
- name: Perform on stdby server
blockinfile:
path: '/home/conf'
marker: "#-- {mark} Adding Values --"
block: |
{{ conf_stdby }}
when: "'host02' in inventory_hostname"
由于每个任务都在所有主机上同时执行,我希望它会在第一个任务中更改 host01,并在第二个任务中跳过 host02,反之亦然,但是它在两个任务中的两个主机中都发生了变化,当我检查服务器都有conf_stdby。
此外,我的剧本中还有许多其他主机共有的任务。
inventory_hostname 不起作用,因为在 playbook 的清单文件中没有 ip 没有主机名,所以有没有办法在什么情况下使用实际主机的主机名?
也试过了
vars:
my_conf:
host01: "{{ conf }}"
host02: "{{ conf_stdby }}"
task:
- name: Perform on primary server
blockinfile:
path: '/home/conf'
marker: "#-- {mark} Adding Values --"
block: |
{{ conf }}
when: ""{{hostvars[inventory_hostname].ansible_hostname}} in myconf"
两个主机仍然添加相同的块
【问题讨论】:
-
还有其他(也是更好的)方法可以解决您的问题,但要坚持您原来的问题“基于主机名执行任务”,这里有一个更好的方法:gist.github.com/zeitounator/2c61c1834e4700ab70ecf609244dbd57
-
感谢@Zeitounator 的回复,我的剧本中有很多常见的任务,所以你提到的链接不能解决目的,我还编辑了我的问题以更新这个细节
标签: ansible ansible-2.x