Search code examples
ansibleansible-2.xansible-inventory

How to grab specific group from ansible inventory and use it in playbook?


I need to grab specific sub group from my inventory file and use it in ansible playbook correctly.

all:
  children:
    development:
      children:
        ntp_servers:
          hosts:
            ntp01:
            ntp02:
        services:
          children:
            chatbot:
              children:
                app:
                  hosts:
                    chatbot-app01:
                    chatbot-app02:
                db:
                  hosts:
                    chatbot-db01:
                    chatbot-db02:
            dice:
              children:
                app:
                  hosts:
                    dice-app01:
                    dice-app02:
                db:
                  hosts:
                    dice-db01:
                    dice-db02:
                    dice-db03:
                redis:
                  hosts:
                    dice-redis01:
                    dice-redis02:

For example I want to grab app subgroup of chatbot group. Can anyone give example playbook how to reference chatbot.app group?

I used like this but this seems to be wrong statement.

- hosts: chatbot:app
  roles:
    - chatbot

Solution

  • It's not directly possible to achieve what you are trying to achieve. The problem you currently have is that the hostgroup names app and db are being repeated, and this will skew your results.

    Firstly you will need to ensure you use unique group names. For example:

    all:
      children:
        development:
          children:
            ntp_servers:
              hosts:
                ntp01
                ntp02
            services:
              children:
                chatbot:
                  children:
                    chatbot_app:
                      hosts:
                        chatbot-app01:
                        chatbot-app02:
                    chatbot_db:
                      hosts:
                        chatbot-db01:
                        chatbot-db02:
                dice:
                  children:
                    dice_app:
                      hosts:
                        dice-app01:
                        dice-app02:
                    dice_db:
                      hosts:
                        dice-db01:
                        dice-db02:
                        dice-db03:
                    dice_redis:
                      hosts:
                        dice-redis01:
                        dice-redis02:
    

    Then you can look at referring to parent/child groups as you see fit. Using the example in your question, you can do:

    - hosts: chatbot_app
      roles:
        - chatbot
    

    The same can be done for all of your groups (development, ntp_servers, services, chatbot, dice, etc)