Wednesday, March 12, 2025

Ansible Blocks with Nested When Statements

inventory.yml
all:
  hosts:
    device1:
      interfaces:
        GigabitEthernet0:
          description: Internet Uplink
        GigabitEthernet0/0/0:
        GigabitEthernet0/0/1:
playbook.yml
---
  - name: Main Play
    hosts: all
    gather_facts: false
    vars:
      ansible_connection: network_cli
      ansible_network_os: ios
    tasks:
      - name: Gather facts
        cisco.ios.ios_facts:
          gather_subset: all
      - name: Configure Interfaces
        when: interfaces is defined
        block:
          - name: Set interface descriptions
            loop: "{{ interfaces | dict2items }}"
            when: item.value.description is defined
            cisco.ios.ios_config:
              lines:
                - "description {{ item.value.description }}"
              parents: "interface {{ item.key }}"

No comments:

Post a Comment