The playbook let’s you to check VLAN existing on Cisco switch, if not creating it for you with add interfaces too as optional.
Note: To give you the impression that how to register data obtained from run-config and compare with true and false using when (defined/undefined). In this way, I can give your ideas to use the same mechanism to solve other tasks, otherwise, not need 22.
- Download and install Ansible Cisco IOS collection on your Linux computer
ansible-galaxy collection install cisco.ios
- Create an empty YAML file and name it create_vlan.yaml with below codes:
# @author [Hawar Koyi] # @email [hawar@koyi.it] # @create date 2021-04-10 15:20:38 # @desc [Automation - Check if VLAN existing, if not create it] --- - name: Create VLAN if don’t exist on a Cisco switch hosts: Cisco gather_facts: false connection: local #Change variables values vars: vlan_id: 35 vlan_name: Guest interface: GigabitEthernet0/2 tasks: #Run show VLAN id "{{ vlan_id }}" and register result. - name: Collect facts about VLAN "{{ vlan_id }}" on device ios_command: commands: show vlan id "{{ vlan_id }}" | section enet register: sh_vlan_output #Check if VLAN it's defined, does not do anything if existing - set_fact: vlan_exists: false when: sh_vlan_output.stdout_lines is defined #Check if VLAN it's undefined, if not then go for below task to Add VLAN - set_fact: vlan_exists: true when: sh_vlan_output.stdout_lines is undefined #Add VLAN with name and interfaces too. - name: Add VLAN using aggregate cisco.ios.ios_vlan: aggregate: - {vlan_id: "{{ vlan_id }}", name: "{{ vlan_name }}", interfaces: "{{ interface }}"} #Save to start-config when modified - name: save running to start-config when modified ios_config: save_when: modified #End of codes
- Create an empty text file and name it hosts with devices IP-addresses and other details.
[Cisco] 192.168.10.122 192.168.xx.xx [Cisco:vars] ansible_connection=network_cli ansible_network_os=ios ansible_user=cisco ansible_password=cisco ansible_become=yes ansible_become_method=enable ansible_become_password=cisco
- Finally run the playbook with this command
ansible-playbook -i hosts create_vlan.yaml
Results looks like the image below.
Extra if you want. Trunk an interface
#Make Gi0/2 mode as trunk - name: Merge provided configuration with device configuration cisco.ios.ios_l2_interfaces: config: - name: GigabitEthernet0/2 mode: trunk trunk: allowed_vlans: 10-20,40 native_vlan: 20 pruning_vlans: 10,20 encapsulation: dot1q state: merged
For more information, check out here: For VLAN cisco.ios.ios_vlan and for Interfaces cisco.ios.ios_l2_interfaces