2

Trying to figure out the best way to get ansible to do its magic within the containers. Was thinking of using ssh in each container, but then that is server-dependent. or I have to come via the proxy which seems like more work than should be necessary. Again, I am already creating containers, deleting etc… I am talking about running commands within the container with ansible not via lxc exec containername bash which I can do now. Anyone figure out the best way to do it.

gzala
  • 31
  • 3

2 Answers2

1

taken from https://docs.ansible.com/ansible/latest/collections/community/general/lxc_container_module.html#examples

you can try the following:

- name: Run a complex command within a "running" container
  community.general.lxc_container:
    name: test-container-started
    container_command: |
      apt-get update
      apt-get install -y curl wget vim apache2
      echo 'hello world.' | tee /opt/started
      if [[ -f "/opt/started" ]]; then
          echo 'hello world.' | tee /opt/found-started
      fi
0

community.general.lxc_container is definitely deprecated and does not support lxd, since it point to bin/lxc-create hard-coded it can not run just commands, maybe commands can be run only during creations.

But is still the only working tool for creating, stooping, and starting the containers in Ansible.

There is a reason why it is not fixed or adjusted to lxd.

There is another easier way to do it, see this official lxd demo LXD and Ansible. Shortly, it is based on the connection type changing from 'ssh' to 'lxd'. Additional pre-configuration is needed when connecting remotely.

#ansible.cfg
[defaults]
inventory = hosts.yml

#hosts.yml all: vars: ansible_connection: lxd ansible_user: root ansible_become: no children: local: vars: ansible_lxd_remote: local ansible_lxd_project: demo hosts: c1: v1: yyy: vars: ansible_lxd_remote: tuxedo hosts: lxc-tuxedo-1: xxx: vars: ansible_connection: ssh ansible_user: ada hosts: alu-rpi:

#demo.yml

  • name: Setup apache hosts: all tasks:

    • name: install the apache package apt: name: apache2 state: present

    • name: Make sure apache is running systemd: name: apache2.service state: started

bash

ansible-playbook demo.yml -l yyy # lxd container via lxd connection ansible-playbook demo.yml -l xxx # rasberry pi via ssh