@@ -492,8 +492,7 @@ def to_dict(self):
492
492
del fields ['cloud_manager' ]
493
493
return fields
494
494
495
- # TODO: strict is unused?
496
- def get_ip (self , access = 'public' , addr_family = None , strict = None ):
495
+ def get_ip (self , access = 'public' , addr_family = None ):
497
496
"""
498
497
Return the server's IP address.
499
498
@@ -505,28 +504,41 @@ def get_ip(self, access='public', addr_family=None, strict=None):
505
504
if addr_family not in ['IPv4' , 'IPv6' , None ]:
506
505
raise Exception ("`addr_family` must be 'IPv4', 'IPv6' or None" )
507
506
508
- if access not in ['private' , 'public' ]:
509
- raise Exception ("`access` must be 'public' or 'private'" )
507
+ if access not in ['private' , 'public' , 'utility' ]:
508
+ raise Exception ("`access` must be 'public', 'utility' or 'private'" )
510
509
511
- if not hasattr (self , 'ip_addresses' ):
512
- self .populate ()
510
+ if not hasattr (self , 'networking' ):
511
+ raise Exception (
512
+ "`networking` attribute is missing, server details must be fetched first"
513
+ )
513
514
514
- # server can have several public or private IPs
515
- ip_addrs = [ip_addr for ip_addr in self .ip_addresses if ip_addr .access == access ]
515
+ ip_addrs = []
516
+ for iface in self .networking ['interfaces' ]['interface' ]:
517
+ iface_ip_addrs = iface ['ip_addresses' ]['ip_address' ]
518
+ if len (iface_ip_addrs ) == 0 :
519
+ continue
516
520
517
- # prefer addr_family (or IPv4 if none given)
518
- preferred_family = addr_family if addr_family else 'IPv4'
519
- for ip_addr in ip_addrs :
520
- if ip_addr .family == preferred_family :
521
- return ip_addr .address
521
+ for ip in iface_ip_addrs :
522
+ if iface ['type' ] == access and (not addr_family or ip ['family' ] == addr_family ):
523
+ ip_addrs .append (ip )
522
524
523
- # any IP (of the right access) will do if available and addr_family is None
524
- return ip_addrs [0 ].address if ip_addrs and not addr_family else None
525
+ # If IP address family has not been defined, we'll prefer v4 when it's available
526
+ if not addr_family :
527
+ for addr in ip_addrs :
528
+ if addr ['family' ] == 'IPv4' :
529
+ return addr ['address' ]
530
+
531
+ # Any remaining IP should be good
532
+ return ip_addrs [0 ]['address' ] if ip_addrs else None
525
533
526
534
def get_public_ip (self , addr_family = None , * args , ** kwargs ):
527
535
"""Alias for get_ip('public')"""
528
536
return self .get_ip ('public' , addr_family , * args , ** kwargs )
529
537
538
+ def get_utility_ip (self , addr_family = None , * args , ** kwargs ):
539
+ """Alias for get_ip('utility')"""
540
+ return self .get_ip ('utility' , addr_family , * args , ** kwargs )
541
+
530
542
def get_private_ip (self , addr_family = None , * args , ** kwargs ):
531
543
"""Alias for get_ip('private')"""
532
544
return self .get_ip ('private' , addr_family , * args , ** kwargs )
0 commit comments