3

How can I use Ansible to execute tasks on lxc containers on a remote server?

We use Ansible to deploy our code on several servers (physical and virtual machines).

Until now, every instance had a public ip address and a running ssh server, so everything worked like a charm. But recently, we had to deploy on two lxc containers on a remote server.

The two containers are natted and don't run a ssh server (and we'd like to keep it that way). I can only connect to them using ssh to reach the physical host then lxc-attach'ing to them.

The only way I found is a custom plugin that was never updated for the latest Ansible 2.0 version. I also reached to the mailing list with no result so far.

Has anybody ever succeeded in using Ansible in such a configuration?

Thibault J
  • 131
  • 1
  • 5

3 Answers3

1

Try the ansible-lxc-ssh connection plugin from Pierre Chifflier, which works with Ansible 2.x. I put the plugin in the default location defined in ansible.cfg, /usr/share/ansible_plugins/connection_plugins/

In the inventory hosts file, /etc/ansible/hosts, I put the following

[containers]
container_01 ansible_host=lxc_server ansible_connection=lxc_ssh ansible_ssh_extra_args=container_01

Note that you have to pass the container name as an ssh extra arg. Be sure to replace lxc_server with the name of your lxc host.

John
  • 11
  • 2
0

I found a simple way that does not require plugins or configuring ssh. It feels klugish, but in my tests it works very well. All that is needed is to change the ansible_python_interpreter variable to run everything within the lxc container. Change name_of_lxc_container, below, to your container's name.

<<< tasks to run on the remote host >>>

- name: BEGIN lxc exec ...
  set_fact:
    ansible_python_interpreter: lxc exec name_of_lxc_container -- /usr/bin/python3

<<< tasks to run in the lxc container >>>

- name: END lxc exec ...
  set_fact:
    ansible_python_interpreter: /usr/bin/python3

<<< more tasks to run on the remote host >>>

Update: this trick does not work with the copy or unarchive modules when copying from controller to remote. Instead, outside of the BEGIN .. END block, use Ansible copy to /tmp and then lxc file push ....

bitinerant
  • 180
  • 5
0

Well, since I couldn'n find a solution, I ended up running a ssh server on every lxc container.

Here's my .ssh/config sample:

Host main_server
    HostName server_address
    User root
    Port 2022
    ForwardAgent yes

Host lxc_container
    User root
    Port 22
    ProxyCommand ssh main_server nc lxc_container 22
    ForwardAgent yes
Thibault J
  • 131
  • 1
  • 5