1. 程式人生 > 實用技巧 >ansible-playbook 修改主機的host解析

ansible-playbook 修改主機的host解析

ansible-playbook 修改主機的host解析

注:ansible 主機同被控主機的互信配置忽略,不在本次討論的範圍內。

1、增加ansible host被控主機資訊

[root@ansible-server ansible_playbook_temple]# more ansiblehosts 
[ansible_hosts]
192.168.1.10
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14

2、測試是否正常

[root@ansible-server ansible_playbook_temple]#ansible ansible_hosts -i ansiblehosts -m ping
192.168.1.10 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.11 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.12 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.13 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.14 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3、操作被控主機的host解析,通過ansible-playbook

增加host解析指令碼

[root@ansible-server ansible_playbook_temple]# more add_hosts.yaml 
---
- hosts: ansible_hosts
  remote_user: root
  tasks: 
  - name: add hosts
    lineinfile:
     path: /etc/hosts
     state: present
     line: "10.10.10.100 www.wanghengzhi.com"
  - name: test hosts
    shell: ping -c2 www.wanghengzhi.com
    register: result
    failed_when: false
  - name: "show result"
    debug:
     msg: "{{result.stdout_lines}}"

執行方式

[root@ansible-server ansible_playbook_temple]#ansible-playbook add_hosts.yaml -i ansiblehosts 

回顯內容略過

修改host解析指令碼

[root@ansible-server ansible_playbook_temple]# more replace_hosts.yaml 
---
- hosts: ansible_hosts
  remote_user: root
  tasks: 
  - name: replace hosts
    lineinfile:
     path: /etc/hosts
     regexp: "10.10.10.100 www.wanghengzhi.com"
     line: "#10.10.10.100 www.wanghengzhi.com"
  - name: test hosts
    shell: ping -c2 www.wanghengzhi.com
    register: result
    failed_when: false
  - name: "show result"
    debug:
     msg: "{{result.stdout_lines}}"

執行方式

[root@ansible-server ansible_playbook_temple]#ansible-playbook replace_hosts.yaml -i ansiblehosts 

回顯內容略過

刪除host解析指令碼

[root@ansible-server ansible_playbook_temple]# more del_hosts.yaml 
---
- hosts: ansible_hosts
  remote_user: root
  tasks: 
  - name: del hosts
    lineinfile:
     path: /etc/hosts
     state: absent
     line: "10.10.10.100 www.wanghengzhi.com"
  - name: test hosts
    shell: ping -c2 www.wanghengzhi.com
    register: result
    failed_when: false
  - name: "show result"
    debug:
     msg: "{{result.stdout_lines}}"

執行方式

[root@ansible-server ansible_playbook_temple]#ansible-playbook del_hosts.yaml -i ansiblehosts 

回顯內容略過