形式类似 10.10.100.0/24
- hosts: "{{ host }}"
gather_facts: false
tasks:
- name: Convert IP to CIDR
shell: python3 -c "import ipaddress; ip = ipaddress.IPv4Address('{{wg_ip}}'); print(ipaddress.IPv4Network(ip, strict=False).supernet(new_prefix=24))"
# shell: python3 -c "import ipaddress; print(ipaddress.IPv4Network('{{wg_ip}}', strict=False).network_address)"
register: network_result
- debug:
var: network_result.stdout
运行:
ansible-playbook playbook/add.yaml \
--extra-vars "host=$host"
PLAY [tmp] ****************************************************************************
TASK [Gathering Facts] ****************************************************************
ok: [tmp]
PLAY [tmp] ****************************************************************************
TASK [Gathering Facts] ****************************************************************
ok: [tmp]
TASK [Convert IP to CIDR] *************************************************************
changed: [tmp]
TASK [debug] **************************************************************************
ok: [tmp] => {
"network_result.stdout": "10.10.10.0/24"
}
PLAY RECAP ****************************************************************************
tmp : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
形式类似 10.10.100.111/32
- hosts: "{{ host }}"
gather_facts: true
tasks:
- name: get CIDR network
debug:
msg: "{{ansible_default_ipv4.address | ansible.utils.ipaddr('network/prefix')}}"
运行:
ansible-playbook playbook/add.yaml \
--extra-vars "host=$host"
PLAY [tmp] ********************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************
ok: [tmp]
TASK [get CIDR network] *******************************************************************************************
ok: [tmp] => {
"msg": "192.168.0.233/32"
}
PLAY RECAP ********************************************************************************************************
tmp : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0