Hi,
LXC containers that I use have cloud-init build in, so that the main way of configuring them.
All example below use LXD as the 'hypervisor'. I spin up a container with one basic profile ('bootstrap') (bound to a network that has full internet access), configure the container (i.e. apply all my roles) and then reconfigure it to the target profile (which usually means different network/IP) and restart.
Tasks to create a container profile:
- name: create a service profile
lxd_profile:
name: service
description: "used for services containers"
state: present
devices:
eth0:
name: eth0
nictype: bridged
parent: vlan3
type: nic
- name: create a bootstrap profile
lxd_profile:
name: bootstrap
description: "used for bootstrapping of containers"
state: present
config: { "user.user-data": "#cloud-config\nssh_authorized_keys:\n - ssh-rsa AAAAB3xxxxx\npackages:\n - openssh-server"}
devices:
eth0:
name: eth0
nictype: bridged
parent: vlan2
type: nic
Playbook to spin up a container and configure it. I pass the final role as a parameter. "gather facts" is off since the container images don't have python by default and I install it manually using role "common".
- name: create container
hosts: "{{ lxdhost | default(t1) }}"
connection: ssh
user: pshemk
become: true
tasks:
- name: build container
register: result
lxd_container:
name: "{{ lxcname }}"
state: started
source:
type: image
properties:
os: "ubuntu"
release: "xenial"
architecture: "amd64"
profiles: ["bootstrap"]
timeout: 600
wait_for_ipv4_addresses: true
- name: update local inventory
delegate_to: 127.0.0.1
connection: local
become: false
copy: content="[{{ lxcname }}]\n{{ result.addresses.eth0[0] }} type=lxc" dest="./inventory/dyn-{{ lxcname }}"
- meta: refresh_inventory
- pause: seconds=60
- name: setup container
hosts: "{{ lxcname }}"
connection: ssh
user: ubuntu
become: true
gather_facts: false
roles:
- common
- resolver
- "{{ lxcrole }}"
- name: restart container
hosts: "{{ lxdhost }}"
connection: ssh
user: pshemk
become: true
tasks:
- name: reasign profile
register: result
lxd_container:
name: "{{ lxcname | default(totara) }}"
state: restarted
profiles: ["{{ hostvars[inventory_hostname]['hosts'][lxcname]['profile'] }}"]
timeout: 600
wait_for_ipv4_addresses: true
- name: update local inventory
delegate_to: 127.0.0.1
connection: local
become: false
copy: content="[{{ lxcname }}]\n{{ result.addresses.eth0[0] }} type=lxc" dest="./inventory/dyn-{{ lxcname }}"
kind regards
Pshem