用于将连续整数指定为主机名的Ansible循环

我是Ansible的新手。 我有以下的剧本改变远程服务器的主机名:

--- - hosts: dbservers remote_user: testuser1 become: yes become_method: sudo vars: LOCAL_HOSTNAME: 'db01' LOCAL_DOMAIN_NAME: 'ansibletest.com' tasks: # Checks and removed the existing occurences of <IP hostname FQDN> from /etc/hosts - name: Remove occurences of the existing IP lineinfile: dest=/etc/hosts regexp='{{ hostvars[item].ansible_default_ipv4.address }}' state=absent when: hostvars[item].ansible_default_ipv4.address is defined with_items: "{{ groups['dbservers'] }}" # Adds the IP in the format <IP hostname FQDN> to /etc/hosts - name: Add the IP and hostname to the hosts file lineinfile: dest=/etc/hosts regexp='.*{{ item }}$' line="{{ hostvars[item].ansible_default_ipv4.address }} {{ LOCAL_HOSTNAME }} {{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}" state=present when: hostvars[item].ansible_default_ipv4.address is defined with_items: "{{ groups['dbservers'] }}" - name: Remove HOSTNAME occurences from /etc/sysconfig/network lineinfile: dest=/etc/sysconfig/network regexp='^HOSTNAME' state=absent when: hostvars[item].ansible_default_ipv4.address is defined with_items: "{{ groups['dbservers'] }}" - name: Add new HOSTNAME to /etc/sysconfig/network lineinfile: dest=/etc/sysconfig/network regexp='^HOSTNAME=' line="HOSTNAME={{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}" state=present when: hostvars[item].ansible_default_ipv4.address is defined with_items: "{{ groups['dbservers'] }}" - name: Set up the hostname hostname: name={{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }} 

在这个例子中, LOCAL_HOSTNAME已经被赋值为db01 。 在这种情况下, dbservers组只有一个服务器:

 [dbservers] 192.168.1.93 

但是,我还有另外两台服务器被指定为web服务器:

 [webservers] 192.168.1.95 192.168.1.96 [dbservers] 192.168.1.93 

目的是将它们命名为web01.domainweb02.domain等。

按照文档看来,这可以通过使用with_sequence来实现。

我的问题是,是否有可能(在Ansible中)在循环中使用2个variables? 下面的伪代码的一些东西:

 i=1 for host in webservers: open host(/etc/hosts): add "IP<space>HOSTNAME{i}<space>"<space>"HOSTNAME{i}.FQDN" i++ 

这是否可以通过使用剧本来实现,还是我以一种错误的方式来处理这个问题?

Solutions Collecting From Web of "用于将连续整数指定为主机名的Ansible循环"

首先生成索引主机名,将其定义为hostfact,稍后使用它来填充其他服务器的主机文件。

 - hosts: webservers gather_facts: no tasks: - set_fact: indexed_hostname: "{{ 'web{0:02d}'.format(play_hosts.index(inventory_hostname)+1) }}" - hosts: dbservers gather_facts: no tasks: - debug: msg: "{{ hostvars[item].indexed_hostname }}" with_items: "{{ groups['webservers'] }}" 

还有这样的事情, with_indexed_items 。