Skip to the content.

15. March 2021 - verfasst von Oliver Gaida - Kategorien: ["ansible"]

Ansible ipaddr Beispiele

Voraussetzungen

eventuell vorher das notwendige Python-Modul installieren

python -m pip install netaddr

lokale Facts dumpen:

ansible localhost -m setup --tree ./

mit jq infos saugen

jq -r '.ansible_facts.ansible_default_ipv4|.network+"/"+.netmask' localhost
192.168.4.0/255.255.255.0

Nun das ganze durch den Filter jagen und zu CIDR konvertieren

ansible localhost -m debug -a "msg={{ net_mask | ansible.netcommon.ipaddr('net') }}" -e net_mask=$(jq -r '.ansible_facts.ansible_default_ipv4|.network+"/"+.netmask' localhost)
localhost | SUCCESS => {
    "msg": "192.168.4.0/24"
}

siehe https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters_ipaddr.html#converting-subnet-masks-to-cidr-notation

cidr im playbook zusammenbauen

---
- name: get network in cidr notation
  hosts: localhost
  gather_facts: yes
  become: no
  tasks:
  - name: print local cidr network
    debug:
      msg: "{{ ansible_default_ipv4 | json_query(query) | ansible.netcommon.ipaddr('net') }}"
    vars: 
      query: "join('/',[network,netmask])"

Output:

TASK [print local cidr network] **********************************
ok: [localhost] => {
    "msg": "192.168.2.0/24"
}
HOME