operator
operator copied to clipboard
ip address getter
It would be very handy if ip addresses could be fetched more easily. For example, in my current use-case, in lieu of a direct ops method, I am using:
@property
def ip_address(self):
relation = self.model.get_relation("replicas")
return str(self.model.get_binding(relation).network.bind_address)
It would be even better if there was no requirement for a relation to obtain IP address of self. To copy and paste a suggestion from the Mattermost channel, something like
def ip(self):
ip = check_output(["unit-get", "private-address"]).decode().strip()
return ip
While the internal implementation does not really matter if it is hidden from the charm writer. But there are two concerns here. The charm may not have declared a peer relation in its metadata. It is a bit counter intuitive that to know the IP address of self requires a relation with another charm.
This is definitely awkward. We have to balance having a simple way to get a single IP address, and being able to handle multiple network interfaces / IP addresses (also dual-stack IPv4 and IPv6).
I recently discovered that the get_binding function doesn't require the relation to be established to work. And, there's a relation known as juju-info present in every charm implicitly.
Thus, to fetch the IP address of a unit in any charm without any prerequisites, you can simply run self.model.get_binding("juju-info").network.bind_address.
Which still is imho a pain to remember and write every time, while we could have a self.unit.ip :)
to fetch the IP address of a unit in any charm without any prerequisites, you can simply run
self.model.get_binding("juju-info").network.bind_address
Neat hack!
After reading the docstrings it seems that self.unit.ip is ambiguous because it could differ per relation.
Regardless, afaict, we no longer use get_binding IP anywhere because:
- fqdn is stable across upgrades
- dns is necessary for TLS
@benhoyt perhaps relation events could have a .network attr for easier access, but I'm closing this for now as it seems we don't really need it.