The ipaddr filter can be used to determine if a string or variable contains a properly formatted IP address. This is often used in conjunction with the fail module and when parameter to fail a play.
For example, let's say demo.yml contain the following.
---
- hosts: localhost
tasks:
- fail:
msg: "{{ ip }} is not a properly formatted IP address"
when: ip | ipaddr == false
...
When running demo.yml using the ansible-playbook command, the -e or --extra-vars command line option can be used to pass an IP address into demo.yml. Let's say an improperly formatted IP address is passed in.
ansible-playbook demo.yml --extra-vars "ip=1234"
The following should be returned.
fatal: [localhost]: FAILED! => {"changed": false, "msg": "1234 is not a properly formatted IP address"}