產生 hosts 檔案

  1. 下載 hosts.j2 樣板檔。
  2. host2.j2 格式為 IP FQDN HOSTNAME (FQDN, Fully qualified domain name, 完整網域名稱),修改 host2.j2 產生所有 inventroy hosts。
    ceuser@deyu:/ansible_pb$ vi hosts.j2
    ceuser@deyu:/ansible_pb$ 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. 查詢 template 模組文件的範例。
    ceuser@deyu:~/ansible_pb$ ansible-doc template | grep ^EX -A8
    EXAMPLES:
    
    - name: Template a file to /etc/file.conf
      ansible.builtin.template:
        src: /mytemplates/foo.j2
        dest: /etc/file.conf
        owner: bin
        group: wheel
        mode: '0644'
    
  4. 建立 playbook 腳本 hosts.yml,當主機在 dev 群組時,使用 hosts.j2 樣板產生 /etc/myhosts。
    ceuser@deyu:/ansible_pb$ vi hosts.yml 
    ceuser@deyu:/ansible_pb$ cat hosts.yml
    ---
    - name: Create /etc/myhosts
      hosts: all
      tasks:
      - name: Template a file to /etc/myhosts
        ansible.builtin.template:
          src: /home/ceuser/ansible_pb/hosts.j2
          dest: /etc/myhosts
        when: '"dev" in group_names'