4

How can I get the IP address of an LXC container in a format I can use in scripting?

Right now, the command lxc info <container> report that information, but in a human readable format, with a lot of information.

I would like to ONLY to GET the IP address given a container name.

Note: I HAVE to duplicate this question because Linux Containers have changed a lot.

Installing lxd and using unprivileged containers is the default way to go this days (2017) and I think the solutions posted on the original question are do not resolve the issue in this case.

In any case, I installed the package lxc1 to get access to the command lxc-info, but that command doesn't recognize any of my unprivileged containers.

2

A native solution (which isn't any prettier than @siloko's answer) would be

lxc list "<name>" -c 4 | awk '!/IPV4/{ if ( $2 != "" ) print $2}'

There are alternatives to awk, but that's tangential to the question.

2
lxc list | grep nameofthecontainer | egrep -o "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"

This is what I am using, I pass the container name in as a variable.

  • 2
    the grep command is unneded, you can put directly lxc list container_name | egrep -o "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" with the same result – Yonsy Solis Feb 20 '18 at 15:45
2

So far this is the easiest way:

lxc list -c4 --format csv <container> | cut -d' ' -f1

But maybe it will be possible without cut.

EDIT: Uncut bash:

a=( $(lxc list -c4 --format csv u1) ) ip4=$a[1] echo $ip4

Hint from @monstermunchkin from the above issue.

2

pylxd is the official python API client interface developed, supported, and endorsed by the LXD project.

Installation instructions here

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
>>> from pylxd import Client
>>> client = Client()
>>> for p in client.containers.all(): print(p.name, p.state().network['eth0']['addresses'][0]['address'])
... 
stretch-cc 10.76.67.242
0

Probably a bit ugly but:

lxc-info -n my-container | grep IP: | tr -d ' ' | cut -f2 -d:

will get you just the IP address

  • Thank you. It would be a solution in the near time. BTW, the idea is to use the command lxc info, not lxc-info as they are different how I explained. – jgomo3 Jun 1 '17 at 14:58
  • bare lxc is not available on my system (Ubuntu 16.04), sorry. – slowko Jun 2 '17 at 6:55
-1
lxc-info --name container --ips --no-humanize

prints the container IP addresses.

The returned value is a list because a container can have more than one address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.