Automation guides, explanations and reader checklists on whilenetworking.com

Ansible Guide: Automating the Creation of VLANs and Subnets Based on Departmental Request Forms

In modern network operations, manual configuration is a primary source of human error and security drift. When a department submits a request form for new…

In modern network operations, manual configuration is a primary source of human error and security drift. When a department submits a request form for new resources—such as a marketing team needing 20 workstations with specific VLAN isolation—the traditional process involves logging into multiple switches, typing commands, and verifying connectivity one by one. This guide demonstrates how to automate this workflow using Ansible. By integrating Python, Bash, and PowerShell logic within playbooks, you can transform static request forms into dynamic network infrastructure changes safely and repeatably.

This article focuses on a realistic workplace scenario where a centralized IT Operations Center receives JSON-formatted requests via an internal web portal or email parser. The goal is to translate these flat data files into active switch configurations without touching the CLI directly. We will explore prerequisites, construct a robust Ansible playbook, and detail verification steps to ensure network stability.

Prerequisites and Environment Setup

Before automating VLAN creation, you must establish a safe test environment. Attempting to run configuration scripts on a production network without rigorous testing can cause outages or security breaches.

Environment Requirements:
* Ansible Version: 2.14 or later (supports structured data handling better).
* Network Devices: Cisco IOS-XE or similar CLI-accessible switches connected to your management network.
* Inventory File: A valid Ansible inventory defining the target switches and their connection groups (e.g., [core], [access]).
* Request Format: Assume a standard JSON file named dept_requests.json resides in /var/www/html/requests/.

Security Considerations:
Never hardcode passwords in your playbook. Use Ansible Vault to encrypt sensitive credentials or integrate with an existing secrets manager like HashiCorp Vault. Always test scripts in a lab environment that mirrors production topology before deployment.

Parsing Departmental Request Forms

The automation begins by reading the input data. In this scenario, the department form generates a JSON payload containing the VLAN ID, subnet mask, gateway, description, and the list of interface names to assign to that VLAN.

# Example content of dept_requests.json
[
  {
    "vlan_id": 105,
    "subnet": "192.168.105.0/24",
    "gateway": "192.168.105.1",
    "description": "Marketing_Q3_Expansion",
    "interfaces": ["Gi0/1", "Gi0/2", "Gi0/3"],
    "source_file": "/var/www/html/requests/marketing_q3.json"
  }
]

Ansible can parse this file using the ansible.builtin.copy module to inject data into a Jinja2 template or by using Python logic within a custom script executed on the controller. For complex parsing, embedding a small Python snippet inside an Ansible task is often cleaner than relying solely on YAML filters.

Configuring VLANs and Interfaces via Playbooks

Once the data is parsed, the playbook must translate logical requirements into physical switch commands. We will use the ansible.netcommon.network_command or specific vendor modules (like cisco.ios.ios_config) to push configurations.

The following snippet demonstrates a generic approach using a Jinja2 template to generate the configuration block dynamically based on the JSON input.

- name: Automate VLAN Creation from Request Forms
  hosts: access_switches
  gather_facts: false
  vars_files:
    - /etc/ansible/dept_requests.json

  tasks:
    - name: Load request data into variable
      set_fact:
        current_request: "{{ dept_requests }}"

    - name: Generate VLAN configuration block
      template:
        src: vlan_config.j2
        dest: /tmp/vlan_config.cfg
      vars:
        # Logic to iterate through the JSON list and build config strings
        config_block: >
          vlan {{ item.vlan_id }}
            name {{ item.description }}
            state active
          interface range {{ item.interfaces | join(',') }}
            switchport mode access
            switchport access vlan {{ item.vlan_id }}
            ip address {{ item.subnet.split('/')[0] }} {{ (item.subnet.split('/')[1]) - 24 }}

Note: The exact syntax above is illustrative. Real-world playbooks often separate VLAN creation from interface assignment to handle complex hierarchies.

Handling Different Operating Systems and Versions

Network automation frequently encounters mixed environments where some switches run Cisco IOS, others run Juniper Junos, and legacy devices use older proprietary OS versions. Ansible handles this through collections and platform-specific logic.

If a device is identified as running an older IOS version that does not support the vlan name command within the global config, the playbook must conditionally adjust the output. You can achieve this by checking facts or using specific conditional logic in your Jinja2 templates.

{% if item.vlan_id > 1000 %}
  ! Older IOS versions may require 'vlan {{ item.vlan_id }} name {{ item.description }}' on a different line structure
  vlan {{ item.vlan_id }}
{% else %}
  vlan {{ item.vlan_id }}
    name {{ item.description }}
{% endif %}

Always verify the software version of your target devices before applying configurations. A command valid on IOS-XE 17 might break on an older 15.x release.

Scheduled Jobs and Workflow Automation

Static playbooks are useful, but true efficiency comes from scheduled automation. Departments may submit forms throughout the day. You can orchestrate this using cron jobs on your Ansible controller to poll a directory every 15 minutes.

Implementation Steps:
1. Create a cron job entry: */15 * * * * /usr/local/bin/ansible-playbook -i inventory.ini vlan_automation.yml --extra-vars "mode=poll".
2. Inside the playbook, use the ansible.builtin.stat module to check if new files exist in the request directory.
3. If a new file is detected and has not been processed (tracked via a timestamp or hash), execute the configuration task.

This approach ensures that network changes happen asynchronously without requiring IT staff to manually trigger scripts every time a form is submitted.

Verification and Common Errors

Automated deployment introduces new failure modes. It is critical to include verification steps in your playbook.

Verification Strategy:
After applying the configuration, run a non-destructive check task using ansible.builtin.command with the check_mode flag equivalent (or simply running show run | section vlan). If the output matches expectations, commit the change; otherwise, revert or alert an operator.

- name: Verify VLAN existence
  command: show vlan brief
  register: vlan_output
  changed_when: false

- name: Alert if VLAN missing (Error Handling)
  fail:
    msg: "VLAN {{ item.vlan_id }} was not found on the switch after configuration."
  when: "'{{ item.vlan_id }}' not in vlan_output.stdout"

Common Errors and Fixes:
* Error: Invalid IP address format.
* Cause: The subnet mask calculation in the JSON or template logic was incorrect.
* Fix: Validate input data before passing it to the template using Python’s ipaddress library.
* Error: Switchport mode access command rejected.
* Cause: The interface is currently a trunk port.
* Fix: Add logic to detect existing trunking and either skip or force conversion based on policy.

Industry Application and Student Practice Task

For industry practitioners, this workflow reduces mean-time-to-onboard (MTTO) for new employees or departments from hours to minutes. It also creates an audit trail: every VLAN creation is logged with the source JSON file, timestamp, and operator identity.

Student Practice Task:
1. Set up a GNS3 or Eve-NG lab with two Cisco virtual switches.
2. Create a local directory requests and place a sample JSON file inside.
3. Write an Ansible playbook that reads the JSON, applies the VLAN config to both switches, and saves the generated config to a log file.
4. Modify the playbook to handle a scenario where the requested VLAN ID already exists (prevent duplicate creation).

Conclusion

Automating VLAN and subnet creation based on departmental request forms bridges the gap between administrative requests and network reality. By leveraging Ansible, Python, and careful workflow design, organizations can eliminate manual CLI errors, ensure consistent security policies, and scale their network infrastructure efficiently. Remember that while automation speeds up deployment, rigorous testing and verification remain the pillars of a stable network environment. Always validate your scripts against your specific hardware versions and consult authoritative documentation before applying changes to production networks.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.