---
# Copy the Bifrost clouds.yaml file and CA certificate (if one is in use) to
# the host. This allows us to access the Ironic and Inspector APIs outside of
# the Bifrost container.
- name: Ensure credentials are available on the host
  hosts: seed
  tags:
    - seed-credentials
  vars:
    openstack_config_dir: "{{ ansible_facts.env.HOME }}/.config/openstack"
  tasks:
    - name: Ensure credentials are available on the host
      when: kolla_enable_bifrost | bool
      block:
        - name: Ensure OpenStack config directory exists
          file:
            path: "{{ openstack_config_dir }}"
            state: directory
            mode: 0700

        - name: Get clouds.yaml from Bifrost container
          command:
            cmd: "{{ container_engine }} exec bifrost_deploy cat /root/.config/openstack/clouds.yaml"
          changed_when: false
          register: clouds_yaml
          no_log: true
          become: "{{ container_engine == 'podman' }}"

        - name: Write clouds.yaml
          copy:
            content: |
              {%- set clouds = clouds_yaml.stdout | from_yaml -%}
              {%- for cloud in clouds.clouds.keys() | list -%}
              {%- if 'cacert' in clouds.clouds[cloud] -%}
              {%- set _ = clouds.clouds[cloud].update({'cacert': openstack_config_dir ~ '/bifrost.crt'}) -%}
              {%- endif -%}
              {%- endfor -%}
              {{ clouds | to_nice_yaml }}
            dest: "{{ openstack_config_dir }}/clouds.yaml"
            mode: 0600

        - name: Copy CA certificate from Bifrost container
          vars:
            clouds: "{{ clouds_yaml.stdout | from_yaml }}"
            cacerts: "{{ clouds.clouds.values() | selectattr('cacert', 'defined') | map(attribute='cacert') | list }}"
          command:
            cmd: "{{ container_engine }} cp bifrost_deploy:{{ cacerts[0] }} {{ openstack_config_dir }}/bifrost.crt"
          changed_when: false
          when: cacerts | length > 0
          become: "{{ container_engine == 'podman' }}"
