---
- hosts: localhost
  tasks:
    - name: Set default value for expected resources
      set_fact:
        tenks_expected_resources: []

    - name: Build list of expected resources
      # takes the form: [{ resource_class: CUSTOM_TEST_RC, amount: 2, traits: [] }, ]
      vars:
        resource:
          amount: "{{ spec.count | int }}"  # this gets converted back to a string
          resource_class: "{{ 'CUSTOM_' ~ spec.ironic_config.resource_class | upper | replace('-', '_') }}"
          traits: "{{ spec.ironic_config.traits | default([]) }}"
      set_fact:
        tenks_expected_resources: >-
          {{ tenks_expected_resources + [resource] }}
      loop: "{{ specs }}"
      when: "'ironic_config' in spec"
      loop_control:
        loop_var: spec

    - block:
      - name: Check that OpenStack credentials exist in the environment
        fail:
          msg: >
            $OS_USERNAME was not found in the environment. Ensure the OpenStack
            credentials exist in your environment, perhaps by sourcing your RC file.
        when: not lookup('env', 'OS_USERNAME')

      - name: Gather list of OpenStack services
        command: >-
          {{ virtualenv_path }}/bin/openstack service list -f json
        register: service_list_output
        changed_when: false

      - name: Include the wait-for-resources role
        include_role:
          name: wait-for-resources
        vars:
          wait_for_resources_required_resources: "{{ tenks_expected_resources }}"
          wait_for_resources_venv: "{{ virtualenv_path }}"
          wait_for_resources_python_upper_constraints_url: >-
            {{ python_upper_constraints_url }}
        # Only attempt to wait for resources when the placement service is running
        when: service_list_output.stdout | from_json | selectattr('Type', 'equalto', 'placement') | list | length >= 1
      when: tenks_expected_resources | length > 0