產生 hosts 檔案

  1. 下載 hosts.j2 樣板檔。
  2. host2.j2 格式為 IP FQDN HOSTNAME (FQDN, Fully qualified domain name, 完全資格域名),修改 host2.j2 產生所有 inventroy hosts。
    [deyu1@kvm19 ansible]$ vim hosts.j2
    [deyu1@kvm19 ansible]$ cat hosts.j2
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1 localhost localhost.localdomain localhost6 localhost6.localdomain
    
    {% for host in groups['all'] %}
    {{ hostvars[host]['ansible_default_ipv4']['address'] }} {{ hostvars[host]
    ['ansible_fqdn'] }} {{ hostvars[host]['ansible_hostname'] }}
    {% endfor %}
    
  3. 建立 playbook 腳本 hosts.yml,當主機在 dev 群組時,使用 hosts.j2 樣板產生 /etc/myhosts。
    [deyu1@kvm19 ansible]$ vim hosts.yml 
    [deyu1@kvm19 ansible]$ cat hosts.yml
    ---
    - name: Create /etc/myhosts
      hosts: all 
      tasks:
      - name: Template a file to /etc/myhosts
        template:
          src: /home/deyu1/ansible/hosts.j2
          dest: /etc/myhosts
        when: '"dev" in group_names'