ansible-playbook设置服务器hostname和/etc/hosts

  |   0 评论   |   0 浏览

一、获取系统可用参数

# show os facts
---
- hosts: localhost
  gather_facts: true
  tasks:
  - name: show os facts
    debug:
      var: ansible_facts

二、用IP进行/etc/hosts的设置

# set-hostname.yaml 
---
- hosts: localhost
  gather_facts: true
  vars:
    host_name: 55.qiweioa.cn
  tasks:
  - name: set hostname
    hostname: 'name={{ host_name }}'
  - name: "add the line to the tail of the file"
    lineinfile:
      dest: /etc/hosts
      line: "{{ ansible_default_ipv4.address }} {{ host_name }}"
    run_once: True
  - name: Replace a localhost entry with our own
    lineinfile:
      path: /etc/hosts
      regexp: '^127\.0\.0\.1'
      line: 127.0.0.1 localhost hostname example.com
      owner: root
      group: root
      mode: '0644'

三、一个实用的playbook例子

---  
- hosts: k8s-cluster
  any_errors_fatal: "{{ any_errors_fatal | default(true) }}"
  vars:
    dns_domain: cluster.local
  tasks:
    - name: populate inventory into hosts file
      blockinfile:
        path: /etc/hosts
        block: |-
          {% for item in (groups['k8s-cluster'] + groups['etcd'] + groups['calico-rr']|default([]))|unique -%}
          {{ hostvars[item]['ip'] }}  {{ item }}.{{ dns_domain }} {{ item }}
          {% endfor %}
        state: present
        create: yes
        backup: yes
        unsafe_writes: yes
        marker: "# Ansible inventory hosts {mark}"


标题:ansible-playbook设置服务器hostname和/etc/hosts
作者:SmiteLi
地址:https://smite.site/articles/2020/03/28/1585373506488.html