我试图从用户输入的主机列表中获取主机名和IP地址,并将这些信息发送到中央服务器。我遇到的主要问题是主机的数量可能会有很大的差异。例如,在第一次运行时,用户可以输入1主机名,第二次运行输入30,下一次输入5。无论用户输入1台还是100台主机,我都希望能够使用单一的游戏手册。
在运行Ansible Tower模板时,通过“额外变量”提示收集主机名:
client_hosts: 'host1,host2'然后在剧本中引用:
- name: Gather client information
hosts:
- "{{ client_hosts | default(omit) }}"
tasks:
- name: Grab client hostname
shell: cat /etc/hostname
register: client_hostname
- name: Grab client IP address
shell: hostname -i | sed -n '1 p'
register: client_ip接下来,我希望将这些IP+主机名添加到特定中央服务器上的文件中(服务器主机名不会更改):
- name: Update server
hosts: central.server
tasks:
- name: Update client host list
lineinfile:
path: /path/to/file
line: "{{ hostvars['client_hosts']['client_ip'] }} - {{ hostvars['client_hosts']['client_hostname'] }}"上面的操作对于单个主机很好,但是当指定了多个主机(例如client_hostname1,2,*)时,我如何循环注册变量呢?当我不知道要提前输入多少主机时,用这些值更新服务器?
发布于 2022-12-22 18:12:55
您可以在您的剧本中使用client_hosts指令循环遍历with_items变量。然后,可以使用循环中的item变量引用每个单独的主机。
下面是一个如何修改您的游戏手册以处理多个主机的示例:
- name: Gather client information
hosts: "{{ client_hosts | default(omit) }}"
tasks:
- name: Grab client hostname and IP address
shell: |
hostname -i | sed -n '1 p' > /tmp/client_ip
cat /etc/hostname > /tmp/client_hostname
register: gather_client_info
become: true
- name: Set client hostname and IP address as variables
set_fact:
client_hostname: "{{ hostvars[item]['gather_client_info'].stdout_lines[1] }}"
client_ip: "{{ hostvars[item]['gather_client_info'].stdout_lines[0] }}"
with_items: "{{ client_hosts | default(omit) }}"
- name: Update server
hosts: central.server
tasks:
- name: Update client host list
lineinfile:
path: /path/to/file
line: "{{ client_ip }} - {{ client_hostname }}"
with_items: "{{ client_hosts | default(omit) }}"这个剧本将循环遍历client_hosts变量中的每个主机,并使用shell模块收集主机名和IP地址。然后使用set_fact模块将这些值设置为变量。最后,它将再次遍历client_hosts变量,并使用lineinfile模块更新中央服务器上的文件,为每个主机提供主机名和IP地址。
希望这能有所帮助。
https://serverfault.com/questions/1118668
复制相似问题