Useful lxc command aliases

Thanks again!

Here is what I would be suggesting to users.

Something missing in LXD is a simple command that gives you shell access to a LXD container, under the non-root account of the container. The Ubuntu containers from the ubuntu: repository have the ubuntu account (created by cloud-init instructions as the container is first started).

I used to suggest to lxc exec mycontainer -- sudo --user ubuntu --login. This can be aliased, with an alias named ubuntu so that a user can just run lxc ubuntu mycontainer and get a non-root shell.

Therefore,

Managing aliases in LXD

You can list, add, rename and remove LXD aliases.

Listing LXD aliases

Run the lxc alias list command to list all aliases. In the following, there are no aliases at all (default).

$ lxc alias list
+-------+--------+
| ALIAS | TARGET |
+-------+--------+

Adding a LXD alias

Let’s create an alias, called list. There is already a lxc list subcommand, therefore we will be hiding the official subcommand. But why do this? First, lxc list produces by default a very wide table so we are going to drop some of the columns. Second, we want to show here how to remove an alias, so we will remove the list alias anyway.

$ lxc alias add list 'list -c ns46'
$ lxc alias list
+-------+---------------+
| ALIAS | TARGET        |
+-------+---------------+
| list  | list -c ns46  |
+-------+---------------+

Now, when you run lxc list, you will get just four columns, n for the Name of the container, s for the State of the container (RUNNING, _STOPPED or something else), and 46 for both the IPv4 and IPv6 IP addresses of the container.

Renaming a LXD alias

Frankly, list is not a good choice for the name of an alias because it masks (hides) the proper lxc list subcommand. Let’s rename the alias to something else.

$ lxc alias rename list ll
$ lxc alias list
+-------+---------------+
| ALIAS | TARGET        |
+-------+---------------+
| ll    | list -c ns46  |
+-------+---------------+

Now you can run the following command to list the containers in a table of four only columns.

$ lxc ll

Removing a LXD alias

We have now decided to remove the ll alias. If you love it though, you may keep it! Here is the command anyway.

$ lxc alias remove ll

To get a non-root shell to a LXD container (Ubuntu container from ubuntu: repository)

Create the following alias, named ubuntu:

lxc alias add ubuntu 'exec @ARGS@ --mode interactive -- /bin/sh -xac $@ubuntu - exec /bin/login -p -f '

Run as:

lxc ubuntu mycontainer

To get a shell to a LXD container (default: root, else specify with $USER)

Create the following alias, named ubuntu:

lxc alias add login 'exec @ARGS@ --mode interactive -- /bin/sh -xac $@${USER:-root} - exec /bin/login -p -f '

Run as (to get a root shell by default):

lxc login mycontainer

Run as (to get a specific $USER shell):

lxc login mycontainer --env USER=ubuntu
1 Like