ansibleansible-collections

Verify that Ansible's Collection dependencies are installed before play begins


I use various Ansible Collections. When the Controller Node does not have them installed (e.g. because I installed ansible-core instead of ansible) then the play breaks halfway.

Is there a way to verify such dependencies before the play begins?


Solution

  • Unfortunately the command ansible-galaxy has no parameter to get clean output or to format it. So one need to do post-processing on the output.

     ansible-galaxy collection list 2>/dev/null | sed '0,/^-.*$/d;s/[ \t]*$//' | tr -s ' ' ','
    

    To prevent using loop and in order to get all installed Ansible Collections for further processing, a minimal example playbook

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      tasks:
    
      - name: Generate Collection Facts
        shell:
          cmd: >-
            echo "Collection,Version";
            ansible-galaxy collection list 2>/dev/null
            | sed '0,/^-.*$/d'
            | sed 's/[ \t]*$//'
            | tr -s ' ' ','
        register: collection_facts
    
      - name: Show Collection Facts
        debug:
          msg: "{{ collection_facts.stdout | community.general.from_csv(dialect='unix') }}"
    

    will create a list of Comma Separated Values (CSV) for further processing.

    To get a clean list output

    Further Documentation


    Regarding your comment

    ... it reports "what's installed". But if I want to know "what's missing" I need to perform more processing on that CSV output?

    Right, depending on what one try to achieve more tests can and/or need to be done. A quick example

      - name: Register Collection Facts
        set_fact:
          collection_facts: "{{ collection_facts.stdout | community.general.from_csv(dialect='unix') }}"
    
      - name: Show Collection Facts
        debug:
          msg: "{{ collection_facts }}"
    
      - name: Show if 'community.general' is installed
        debug:
          msg: "Is installed"
        when: collection_facts | selectattr(search_key,'equalto',search_val) | list | count > 0
        vars:
          search_key: Collection
          search_val: community.general
    

    Thanks To


    How to proceed further?

    There was a similar question in the past about What Ansible command to list or verify installed modules — whether built-in or add-on? which has a good solution to create a dictionary of installed collections and modules.