---
- name: Erstelle LXC
  hosts: lokal
  vars:
    lxc_containers:
      - ansible-lxc
      - db2
      - web
      - informaticker

  tasks:
  - name: Erstelle ansible lxc
    become: yes
    lxc_container:
      name: "{{ item }}"
      state: started 
    loop: "{{ lxc_containers }}"
    register: ansible_lxc_container

  - debug:
      var: item
    loop: "{{ ansible_lxc_container['results'] }}"
    when: ansible_lxc_container is changed

  - name: Dienste neustarten
    become: yes
    service:
      name: "{{ item }}"
      state: restarted
    loop:
      - lxc-net
      - systemd-resolved
    when: ansible_lxc_container is changed

  - name: Make a break
    pause:
      seconds: 20
    when: ansible_lxc_container is changed

  - name: Erstelle ansible lxc
    become: yes
    lxc_container:
      name: "{{ item }}"
      state: started
    register: ansible_lxc_container
    loop: "{{ lxc_containers }}"

  - debug:
      var: ansible_lxc_container

  - name: Erstelle lxc-inventory
    copy:
      dest: lxc_inventory
      content: |
              [lxc]
              [lxc:vars]
 
  - name: Hosteinträge
    lineinfile:
      path: lxc_inventory
      insertbefore: [lxc:vars]
      regexp: "^{{ item.lxc_container.name }}       ansible_host={{ item.lxc_container.ips[0] }}"
      line: "{{ item.lxc_container.name }}       ansible_host={{ item.lxc_container.ips[0] }}"
    loop: "{{ ansible_lxc_container['results'] }}"

  - name: Gruppenvariablen anhängen
    blockinfile:
      path: lxc_inventory
      insertafter: [lxc:vars]
      block: |
              ansible_user=ubuntu
              ansible_password=ubuntu
              ansible_ssh_common_args="-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
              ansible_become_pass=ubuntu
...

# Bootstrapping neues Verzeichnis mit ansible.cfg und Inventory Datei
# ansible --inventory localhost, --connection=local --module-name copy --args="dest=ansible.cfg content=[defaults]\ninventory=my_hosts\n" localhost
# ansible --inventory localhost, --connection=local --module-name copy --args="dest=my_hosts content=[lokal]\nlocalhost\tansible_connection=local\n" localhost
