How to edit /etc/netplan/50-cloud-init.yaml with Ansible in LXC container

I have a playbook to create a container:

- name: Create LXD Container #1
  become: True
  lxd_container:
    name: "{{ lxc_CT_NAME }}"
    state: started
    source:
      type: image
      mode: pull
      server: "{{ lxc_image_source }}"
      protocol: simplestreams
      alias: "{{ lxc_container_distro }}"
    profiles: "{{ lxc_profiles }}"
    wait_for_ipv4_addresses: true
    timeout: 10
  when: lxc_lxd_host is defined
  register: container_created

After creating my containers has configaration file /etc/netplan/50-cloud-init.yaml as:

network:
    version: 2
    ethernets:
        eth0:
            dhcp4: true

My goal, edit this file in LXC container, and add new configuration:

network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      addresses:
        - 192.168.100.119/24
      gateway4: 192.168.100.11
      mtu: 1400
      nameservers:
          addresses:
          - 208.**.222.***
          - 208.**.***.220

I tried to use module container_command: and container_config: but can not understand exactly code of this modules.

Could you please help with advice, how to edit file into LXC container using Ansible?


Solution 1:

One way is to add the information to cloud-init to configure the container:

- name: Create LXD Container #1
    become: True
    lxd_container:
    name: "{{ lxc_CT_NAME }}"
    state: started
    source:
      type: image
      mode: pull
      server: "{{ lxc_image_source }}"
      protocol: simplestreams
      alias: "{{ lxc_container_distro }}"
    profiles: "{{ lxc_profiles }}"
    config:
      user.network-config: |
      version: 2
      renderer: networkd
      ethernets:
        eth0:
          dhcp4: false
          dhcp6: false
          addresses:
            - 192.168.100.119/24
          routes:
            - to: 0.0.0.0/24
              via: 192.168.100.11
          nameservers:
            search:
              - example.org (YOUR-DOMAIN-SUFFIX)
            addresses:
              - 192.168.100.1 (YOUR-DNS-SERVER)
    wait_for_ipv4_addresses: true
    timeout: 10
  when: lxc_lxd_host is defined
  register: container_created