iT邦幫忙

0

Ansible 基于 IP 地址修改主机名

  • 分享至 

  • xImage

我这里有要给 ansible 脚本:

---
- name: Change Host Name
  hosts: all
  tasks:
    - name: change host name
      shell: hostnamectl set-hostname master1
      when: hostvars[inventory_hostname]['ansible_facts']['default_ipv4']['address'] == "192.168.1.10"
    - name: change host name
      shell: hostnamectl set-hostname master2
      when: hostvars[inventory_hostname]['ansible_facts']['default_ipv4']['address'] == "192.168.1.11"
    - name: change host name
      shell: hostnamectl set-hostname master3
      when: hostvars[inventory_hostname]['ansible_facts']['default_ipv4']['address'] == "192.168.1.12"
    - name: change host name
      shell: hostnamectl set-hostname worker1
      when: hostvars[inventory_hostname]['ansible_facts']['default_ipv4']['address'] == "192.168.1.13"
    - name: change host name
      shell: hostnamectl set-hostname worker2
      when: hostvars[inventory_hostname]['ansible_facts']['default_ipv4']['address'] == "192.168.1.14"
    - name: change host name
      shell: hostnamectl set-hostname worker3
      when: hostvars[inventory_hostname]['ansible_facts']['default_ipv4']['address'] == "192.168.1.15"

现在已经可以更主机名了,但这样的话,不太灵活,我想通过一个变量文件 hosts_list.yaml,在变量文件中定义 IP 和主机名之间的关系,如:

---
hosts:
  - ip: 192.168.1.10
    hostname: master1
  - ip: 192.168.1.11
    hostname: master2
  - ip: 192.168.1.12
    hostname: master3
  - ip: 192.168.1.13
    hostname: worker1
  - ip: 192.168.1.14
    hostname: worker2
  - ip: 192.168.1.15
    hostname: worker3

然后在 Ansible 中通过脚本去循环调用,通过 when 去指定,当 ip 是多少,主机名就是什么,这个可以实现吗?应该怎么做?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答