我需要知道清单中主机名的索引。我正在使用下面的代码创建一个变量文件,以便在后续的实战手册中使用
- name: Debug me
hosts: hosts
tasks:
- debug: msg="{{ inventory_hostname }}"
- debug: msg="{{ play_hosts.index(inventory_hostname) }}"
- local_action: 'lineinfile create=yes dest=/tmp/test.conf
line="host{{ play_hosts.index(inventory_hostname) }}=
{{ inventory_hostname }}"'我有以下清单文件
[hosts]
my.host1.com
my.host2.com现在,当我运行这段代码时,在/tmp下生成的test.conf有时会有两个主机名,如下所示
host1= my.host2.com
host0= my.host1.com当我多次运行相同的剧本时,每次都在运行之前清空test.conf。很多时候,文件只有一个条目
host1= my.host2.com或
host0= my.host1.com为什么同样的ansible剧本表现不同?
发布于 2017-04-29 05:18:43
我认为问题在于您在不同的主机上运行两个线程,并且使用local_action不是线程安全的。
尝试使用序列关键字:
- name: Debug me
hosts: hosts
serial: 1
tasks:
- debug: msg="{{ inventory_hostname }}"
- debug: msg="{{ play_hosts.index(inventory_hostname) }}"
- local_action: 'lineinfile create=yes dest=/tmp/test.conf
line="host{{ play_hosts.index(inventory_hostname) }}=
{{ inventory_hostname }}"'编辑:如果只是试图对本地主机上的清单中的主机列表进行操作,一种更好的方法是避免在主机上执行该操作,并首先使用local_action。
- name: Debug me
hosts: localhost
tasks:
- lineinfile:
create: yes
dest: /tmp/test.conf
line: "host{{ groups['hosts'].index(item)}}={{ item }}"
with_items: " {{ groups['hosts'] }}"这会让你得到你想要的结果。然后,您可以添加另一个play来对主机本身执行操作。
发布于 2019-07-25 21:37:33
我的解决方案是用非线程安全的Local_action: lineinfile将收集的数据写入本地文件来避免竞争条件的问题。在同一个文件中将其分成两个不同的播放。
例如:
- name: gather_date
hosts: all
any_errors_fatal: false
gather_facts: no
tasks:
- name: get_Aptus_device_count_list
shell: gather_data.sh
become: true
register: Aptus_device_count_list
changed_when: false
- name: Log_gathered_date
hosts: all
any_errors_fatal: false
gather_facts: no
tasks:
- name: log_gathered_info
local_action:
module: lineinfile
dest: /home/rms-mit/MyAnsible/record_Device_count_collection.out
line: "\n--- {{ inventory_hostname }} --- \n
{{ Aptus_device_count_list.stdout }} \n.\n---\n"
changed_when: falsehttps://stackoverflow.com/questions/43683862
复制相似问题