Skip to content

Instantly share code, notes, and snippets.

@MarshalW
Last active November 28, 2023 09:09
Show Gist options
  • Save MarshalW/06589de9584a95db8a1cae425c91540f to your computer and use it in GitHub Desktop.
Save MarshalW/06589de9584a95db8a1cae425c91540f to your computer and use it in GitHub Desktop.
Ansible 脚本获取 ip 地址的 CIDR 网络表示

Ansible 脚本获取 ip 地址的 CIDR 网络表示

网络地址

形式类似 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 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment