Dave0
Dave0

Reputation: 133

How to use hostvars from dynamic inventory

i'm trying to use some hostvars from a dynamic inventory (netbox) in a play. Not sure if this is possible or not. The dynamic inventory looks like this:

{
    "_meta": {
        "hostvars": {
            "switch1.lab1": {
                "ansible_host": "192.168.1.6",
                "device_roles": [
                    "TOR Switch"
                ],
                "device_types": [
                    "EX4300-48T"
                ],
                "manufacturers": [
                    "Juniper"
                ],
                "primary_ip4": "192.168.1.6",
                "sites": [
                    "LAB1"
                ],
                "tags": [
                    "lab"
                ]
            }
        }
    },
    "all": {
        "children": [
            "device_roles_TOR Switch",
            "ungrouped"
        ]
    },
    "device_roles_TOR Switch": {
        "hosts": [
            "switch1.lab1"
        ]
    }
}

And i'm trying to use the "sites" and "tags" section my main.yaml file like this:

 tasks:
   - include_tasks: lab-switch-update.yaml
     when:
      - (hostvars['sites'] == "LAB1")
      - (hostvars['tags'] == "lab")

but when running the play, it keeps skipping because:

TASK [include_tasks] ********************************************************************************************************************************************************
skipping: [switch1.lab1] => {"changed": false, "skip_reason": "Conditional result was False"}

PLAY RECAP ******************************************************************************************************************************************************************
switch1.lab1              : ok=0    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

Any suggestions what i'm missing here?

Upvotes: 2

Views: 902

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Both sites and tags are lists. The play is running at switch1.lab1

The correct condition is

 when:
  - sites.0 == 'LAB1'
  - tags.0 == 'lab'

, or (better)

  when:
    - ('LAB1' in sites)
    - ('lab' in tags)


Note. tags is reserved word. These should not be used as a variables.

Upvotes: 1

Related Questions