Automation guides, explanations and reader checklists on whilenetworking.com

Ansible Playbook: Automating the Migration of Users from Deprecated VLANs to New Segments Based on Departmental Tags

Network segmentation is a critical component of enterprise security and operational efficiency. However, legacy environments often suffer from "VLAN sprawl,"…

Network segmentation is a critical component of enterprise security and operational efficiency. However, legacy environments often suffer from “VLAN sprawl,” where users remain trapped in deprecated Virtual Local Area Networks (VLANs) due to manual change management processes that are slow and error-prone. Automating the migration of these users based on departmental tags using Ansible offers a robust solution. This approach leverages configuration management to ensure consistency, reduce downtime, and enforce security policies without human intervention.

For IT students and junior engineers, understanding how to orchestrate network changes via code is a vital skill. For industry practitioners, this playbook serves as a template for handling large-scale transitions safely. The following guide details a realistic lab scenario where users tagged with specific department identifiers (e.g., dept:engineering, dept:hr) are automatically moved from an old VLAN to a new one over a defined period.

Understanding the Migration Architecture

Before writing code, it is essential to define the prerequisites and the logical flow of the automation. In this scenario, we assume a hybrid environment where user attributes are stored in a lightweight directory service or a simple JSON file for demonstration purposes, as integrating with LDAP/Active Directory requires specific schema extensions.

Prerequisites:
* Ansible Controller: A Linux machine (Ubuntu 22.04 or RHEL 9) running Ansible 2.14+.
* Inventory File: An inventory defining the target network devices (switches/routers) and the source of user data.
* Departmental Tags: A mechanism to identify users, such as a CSV file with columns username, department, current_vlan, and target_vlan.
* Network Devices: Layer 3 switches or VLAN-aware routers supporting Ansible modules like ios_interfaces or nxos_vpc_interface.

The Logic of Departmental Tagging

The core logic of this playbook relies on mapping department names to specific IP subnets (VLANs). Instead of hardcoding every user’s MAC address, the automation reads a “source of truth” file. This file contains metadata tags that dictate network placement.

Example Data Structure:
Imagine a CSV file named user_migration.csv:

username,department,current_vlan,target_vlan
jsmith,engineering,10,200
alopez,hr,15,300
mking,finance,10,400

The Ansible script will parse this file. If a user’s department matches the criteria for the “New Engineering Segment,” the script triggers a move from VLAN 10 to VLAN 200. This ensures that users moving between departments (e.g., an engineer joining HR) are automatically placed in the correct network segment without manual ticket creation.

Developing the Ansible Playbook

The following playbook demonstrates the automation logic. It uses standard Ansible modules to handle file parsing and device configuration. Note that for a production environment, you would replace the generic switch commands with vendor-specific modules (e.g., cisco.nxos.nxos_vlans or ansible.netcommon.config).

---
- name: Migrate Users from Deprecated VLANs to New Segments
  hosts: network_devices
  gather_facts: false
  vars:
    # Define the mapping of department names to new VLAN IDs
    vlan_mapping:
      engineering: 200
      hr: 300
      finance: 400
      marketing: 500

    # Path to the CSV file containing user data
    user_data_file: "/etc/ansible/user_migration.csv"

  tasks:
    - name: Include local inventory or load external data
      ansible.builtin.include_vars: "{{ user_data_file }}"
      delegate_to: localhost

    - name: Parse user migration data
      ansible.builtin.set_fact:
        users_to_migrate: "{{ user_data | dict2items }}"
      run_once: true

    - name: Validate CSV format before processing
      ansible.builtin.fail:
        msg: "Migration file missing required columns: username, department, current_vlan, target_vlan"
      when: "'department' not in user_data.columns"

    - name: Iterate through users to prepare migration commands
      ansible.builtin.debug:
        var: item
      loop: "{{ users_to_migrate.values }}"
      loop_control:
        label: "{{ item.value.department }} ({{ item.value.username }})"

    - name: Construct VLAN membership command for target switch
      # In a real scenario, this would use specific vendor modules to modify interface access-lists or VLAN assignments
      ansible.builtin.command: 
        cmd: "configure terminal"
        args:
          creates: /tmp/migration_session.{{ inventory_hostname }}
      delegate_to: "{{ item.value.target_vlan }}" # Logic placeholder for target device selection
      loop: "{{ users_to_migrate.values }}"
      register: migration_commands

    - name: Display generated commands for review
      ansible.builtin.debug:
        msg: "Would execute on {{ inventory_hostname }}: move user {{ item.value.username }} from VLAN {{ item.value.current_vlan }} to VLAN {{ vlan_mapping[item.value.department] }}"
      loop: "{{ users_to_migrate.values }}"

Implementing Safe Migration Steps

Executing network changes directly can be dangerous. A safe migration workflow involves a “dry-run” phase followed by a staged execution. The playbook above generates the necessary commands but does not execute them blindly.

Step-by-Step Implementation:
1. Dry Run Mode: Modify the ansible.builtin.command tasks to use check_mode: true. This allows administrators to review exactly which users will be moved and on which devices without applying changes.
2. Staged Execution: Implement a loop that processes one department at a time. For example, migrate all Engineering users first, wait for verification, then proceed to HR.
3. Rollback Mechanism: Include a task that reverts the VLAN assignment if the migration count does not match expectations or if an error occurs during the transition.

Expected Output (Illustrative):
When running with --check, you might see:

TASK [Display generated commands for review] *********************************************************************************************************************************
ok: [core-sw-01] => {
    "msg": "Would execute on core-sw-01: move user jsmith from VLAN 10 to VLAN 200"
}

Verification and Validation Procedures

After the migration logic is defined, verification is crucial to prevent service disruption. You must confirm that traffic flows correctly in the new VLANs and that users retain connectivity.

Verification Steps:
1. Ping Tests: From a management station, ping IP addresses assigned to migrated users within their new subnet. Ensure the route table on the core switch has updated paths.
2. VLAN Membership Check: Use CLI commands like show vlan brief or show interface status on the target switches to confirm that ports associated with migrated users are tagged correctly to the new VLAN ID.
3. Application Connectivity: Verify that internal services (e.g., file servers, printers) accessible only within specific departmental VLANs can still be reached by the migrated users.

Common Errors and Troubleshooting

Even well-planned automations encounter issues. Here are common pitfalls and their fixes:

  • Error: AnsibleUndefinedVariable when accessing a department key in vlan_mapping.
    • Fix: Ensure all departments in the CSV file exist as keys in the vars section of the playbook. Add a default value or an explicit error message for unknown departments.
  • Error: IP address conflicts in the new VLAN.
    • Fix: Before migration, ensure the DHCP scope for the new VLAN is configured with a sufficient range to accommodate the incoming users without overlapping existing static IPs.
  • Error: Users lose connectivity during the switch-over.
    • Fix: Implement a “cutover window” where both old and new VLAN assignments exist briefly (if supported by the hardware) or schedule migrations during off-hours. Always test on a non-production switch first.

Student Practice Task and Industry Application

For Students:
Set up a GNS3 or Eve-NG lab with two virtual routers acting as gateways for VLAN 10 and VLAN 200. Create a simple text file acting as your “directory service.” Write an Ansible playbook that reads this file, updates the router configuration to add new subnets, and simulates user movement. Focus on mastering the ansible.builtin.lineinfile or equivalent modules to modify routing tables.

For Industry Practitioners:
Integrate this playbook into your scheduled job workflow (e.g., cron jobs or Jenkins pipelines). Configure it to run weekly to check for users whose department tags have changed but who haven’t been migrated yet. This ensures that organizational restructuring is reflected in the network topology immediately, maintaining security boundaries and compliance requirements.

By automating VLAN migrations based on departmental tags, organizations can eliminate manual errors, speed up onboarding, and ensure that their network architecture evolves as quickly as their business needs change. Always remember to validate every change in a non-production environment before applying it to your live network infrastructure.

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.