Test that a variable is a valid IP address

2,167 views
Skip to first unread message

Ryan Groten

unread,
Jul 28, 2016, 5:19:29 PM7/28/16
to Ansible Project
I'm trying to create a task that verifies a variable is a valid IP address.  The task should pass if it is valid, and fail if it's not.
I feel like I'm close, but not quite there with this:

  - name: Verify IP address
   
assert: { that: "{{ requested_ip | ipaddr }}" }
    always_run
: yes


This task fails properly when the value is not an IP (ipaddr filter returns False), but if it IS an IP it tries to evaluate the ip itself and throws an error (ipaddr returns the IP itself):

TASK [Verify IP address] **************************** fatal: [localhost]: FAILED! => {"failed": true, "msg": "The conditional check '10.1.4.232 != False' failed. The error was: error while evaluating conditional (10.1.4.232 != False): float object has no element 4"}

 Any suggestions?

Thanks,
Ryan

Kai Stian Olstad

unread,
Jul 28, 2016, 5:45:29 PM7/28/16
to ansible...@googlegroups.com
According to the documentation, "that" has the same format as "when".
Since you shouldn't use curly brackets in "when" , you should probably
not use them in "that".

Try
assert: { that: requested_ip | ipaddr }
and see if that fixes it.

--
Kai Stian Olstad

Ryan Groten

unread,
Jul 29, 2016, 11:51:14 AM7/29/16
to Ansible Project, ansible-pr...@olstad.com
Yep that was it, thanks a lot!

sirkubax

unread,
Apr 19, 2018, 3:19:38 AM4/19/18
to Ansible Project
I have a case (IP with a space in a string)

vars:
    requested_ip: '1 .2.3.4'   #  note a space in a string

tasks:
  - name: Verify IP address
    
assert: { that: "{{ requested_ip | ipaddr }}" }
    always_run
: yes

--------------
ok: [18.130.41.1] => {
    "changed": false, 
    "failed": false, 
    "msg": "All assertions passed"

Jakub x

unread,
Apr 19, 2018, 3:27:15 AM4/19/18
to Ansible Project
This works, but it is not 'all in one'

   - name: Verify IP address
     assert:
       that:
         - requested_ip | ipaddr
         - not ' ' in requested_ip
Reply all
Reply to author
Forward
0 new messages