Hello Team.
I have an Ansible playbook where am trying to automate VLAN mapping on my network.
Cureently, script is able to create and map VLAN on respective interfaces as set in the inventory. If one switch in the inventory has VLAN already, it aborts the process and goes to the next switch and if it does nit have then VLAN is created and mapped.
I need it to work in a manner that if VLAN exists in at least one switch, process should be aborted and playbook stopped.
/
-
name: Gather VLAN facts from Cisco devices
hosts: cisco
gather_facts: falsevars_files:
- /var/MIKROTIK/cisco/inventory
vars_prompt:
- name: “username”
prompt: “Enter User Name”
private: no
- name: “password”
prompt: “Enter your password”
private: no
-
name: “VLAN”
prompt: “Enter VLAN ID to add”
private: no -
name: “NAME”
prompt: “Enter VLAN ID Name”
private: no
vars:
- ansible_user:
- ansible_password:
tasks:
- name: Check if VLAN exists
nxos_command:
commands:
- show vlan id {{ VLAN }}
register: vlan_output
ignore_errors: true
- name: Display message if VLAN exists on any switch
fail:
msg: “VLAN {{ VLAN }} already exists on {{ item }}. Aborting VLAN addition.”
loop: “{{ ansible_play_batch }}”
when: vlan_output.stdout is search(‘VLAN {{ VLAN }}’)
-
name: Fail if VLAN already exists
block:-
name: Set fact whether VLAN exists
set_fact:
vlan_exists: “{{ vlan_output.stdout | search(‘VLAN\s+’ + VLAN + ‘\s+’) is not none }}”
delegate_to: localhost -
name: Fail if VLAN exists
fail:
msg: “VLAN {{ VLAN }} already exists on {{ inventory_hostname }}. Aborting VLAN addition.”
when: vlan_exists
when: vlan_output is succeeded
-
-
name: Adding VLAN ID to Database
nxos_vlans:
config:
- vlan_id: “{{ VLAN }}”
name: “{{ NAME }}”
state: active
register: vlan_added
when: vlan_output is failedwhen: vlan_output.stdout is not search(‘VLAN {{ VLAN }}’)
when: “‘VLAN {{ VLAN }} not found in current VLAN database’ in vlan_output.stdout”
-
name: Send notification if VLAN already exists
community.general.mattermost:
text: “VLAN {{ VLAN }} already exists on {{ ansible_host }}. Aborting VLAN addition.”
when: vlan_output is succeeded -
name: Debug vlan_output variable
debug:
var: vlan_output -
name: Debug etherports variable
debug:
var: etherports -
name: Merge provided configuration with device configuration
cisco.ios.ios_l2_interfaces:
config:
- name: “{{ item }}”
mode: trunk
trunk:
allowed_vlans: “{{ VLAN }}”
state: merged
loop: “{{ etherports }}” -
name: Send notification message via Mattermost if VLAN is added
community.general.mattermost:text: |
{% if vlan_added.changed %}
VLAN {{ VLAN }} added successfully!
Has been tagged to {{ ansible_host }} by User {{ ansible_user }} on the following interfaces:
{{ etherports }}
{% else %}
VLAN {{ VLAN }} was not added as it already exist on host {{ ansible_host }}. Please use a new VLAN_ID, thank you!!
{% endif %}