Ansible Playbooks: YAML, Inventory, and Safe Automation

NetOps Tools · Technical Network Automation Guide

Automate the routine.
Keep control of the network.

A practical introduction to Ansible playbooks, inventories, YAML and safer network configuration backups — from first draft to controlled execution.

InventoryWhich devices are targeted
PlaybookWhat tasks are requested
ValidationWhat you review before a run

Ansible helps infrastructure and network teams perform repeatable work across multiple devices. But generating YAML does not automatically create a safe deployment: inventory scope, collections, credentials, change review and device support still matter. This guide uses a documented Cisco IOS example for network automation, and keeps the distinction between reading configuration and changing configuration clear.

1. What makes an Ansible playbook work?

An Ansible inventory identifies the managed hosts or groups. A playbook contains one or more plays; each play selects hosts and lists tasks. A module performs an action or checks a desired state. Modules are commonly referenced using a fully qualified collection name (FQCN), such as cisco.ios.ios_command.

01 · TARGETSInventory

Groups, host addresses, connection details and related variables.

02 · LOGICYAML playbook

Plays and ordered tasks that define the intended work.

03 · EXECUTIONModules

Device-specific commands or declarative state operations.

Traditional Ansible modules can configure Linux hosts over SSH. Network devices often use a network-specific connection plugin, such as ansible.netcommon.network_cli, and modules supplied by vendor collections. Ansible generally runs from a controller; you do not need to install the Ansible control software on each network switch.

2. Create a predictable inventory

Use descriptive groups and keep your production scope separate from a lab. This INI example shows a group called edge_switches with two illustrative Cisco IOS devices. The 192.0.2.0/24 address block is reserved for documentation; replace these values only with devices you are authorized to manage.

inventory.ini · INI
[edge_switches]
sw-lab-01 ansible_host=192.0.2.10
sw-lab-02 ansible_host=192.0.2.11

[edge_switches:vars]
ansible_connection=ansible.netcommon.network_cli
ansible_network_os=cisco.ios.ios
ansible_user=automation
What the variables mean: ansible_connection chooses the network CLI connection; ansible_network_os selects the device platform; ansible_user identifies the account. Credentials must be supplied securely rather than copied into a public article or repository.

Inventory does not discover devices automatically in this example. A play targeting edge_switches can affect every matched host unless you restrict it, so verify the group and use --list-hosts before a sensitive run.

3. Read the structure of a YAML playbook

YAML indentation is meaningful. Use spaces consistently, do not use tabs for indentation, and keep lists aligned. The following playbook uses one play, two tasks and a registered result. It deliberately requests information rather than configuration changes.

show-version.yml · YAML
---
- name: Read version information from lab switches
  hosts: edge_switches
  gather_facts: false
  tasks:
    - name: Request device version
      cisco.ios.ios_command:
        commands:
          - show version
      register: version_result

    - name: Display returned version output
      ansible.builtin.debug:
        var: version_result.stdout[0]

Play-level settings

hosts selects the inventory group. gather_facts: false avoids the default facts-gathering step, which may not suit a network CLI device.

Task-level settings

cisco.ios.ios_command issues the read-only command. register stores the result for the following debug task.

Important: This example expects the appropriate cisco.ios and ansible.netcommon collections, reachable authorized devices and working authentication. It has been checked for YAML structure but not executed against live network equipment.

4. Start with a read-only network check

The safest introduction is to inspect a known lab switch before automating a change. Ansible sends the specified command using the selected connection plugin and receives output from that device. The show version command in the example above is intended as a read-only status query.

Check the targets first · Shell
ansible-playbook -i inventory.ini show-version.yml --list-hosts
ansible-playbook -i inventory.ini show-version.yml --syntax-check
ansible-playbook -i inventory.ini show-version.yml --list-tasks

Once you have reviewed the devices, module compatibility and credentials, run it only in a permitted test environment:

Example controlled lab run · Shell
ansible-playbook -i inventory.ini show-version.yml --limit sw-lab-01
Authorization and scope: Even read-only network commands can create device load or expose sensitive metadata. Work only on infrastructure you own or are explicitly allowed to administer, and follow your organization’s change and access policies.

5. Build a controlled configuration backup

A backup playbook can collect a configuration from each supported switch and save it on the Ansible controller. The following example illustrates the workflow with cisco.ios.ios_command and delegated local file operations. It reads the device’s configuration; it does not push a new one.

backup-config.yml · YAML
---
- name: Back up authorized Cisco IOS devices
  hosts: edge_switches
  gather_facts: false
  tasks:
    - name: Create a private local backup directory
      ansible.builtin.file:
        path: "{{ playbook_dir }}/backups"
        state: directory
        mode: "0700"
      delegate_to: localhost
      run_once: true

    - name: Read the active configuration
      cisco.ios.ios_command:
        commands:
          - show running-config
      register: running_config
      no_log: true

    - name: Save configuration on the controller
      ansible.builtin.copy:
        content: "{{ running_config.stdout[0] }}\n"
        dest: "{{ playbook_dir }}/backups/{{ inventory_hostname }}.cfg"
        mode: "0600"
      delegate_to: localhost
      no_log: true
Illustrative example; review device permissions, collection versions, secure backup storage and local filesystem ownership.
Expected local file layout
  • inventory.ini — authorized targets and connection variables
  • backup-config.yml — tasks for retrieval and local storage
  • backups/sw-lab-01.cfg — saved device configuration
  • backups/sw-lab-02.cfg — saved device configuration

The run_once directory task prepares the destination before the parallel per-host copies. For basic direct execution this is a convenient pattern; execution strategies, delegation, controller permissions and filesystem behavior should be tested in your environment. The example intentionally does not include an automatic restore operation.

Protect backup files: running configurations can include secrets or sensitive network details. no_log: true limits Ansible task output but does not encrypt the saved file. Store backups in access-controlled, encrypted storage with a retention policy; do not upload them to a public site or commit them to Git.

6. Validate scope, syntax and expected behavior

A valid YAML file is not proof that a playbook is safe for your environment. Syntax checks, target listing, task review and an approved lab test answer different questions. These commands support a staged review.

Validation commands · Shell
ansible-playbook -i inventory.ini backup-config.yml --syntax-check
ansible-playbook -i inventory.ini backup-config.yml --list-hosts
ansible-playbook -i inventory.ini backup-config.yml --list-tasks
ansible-playbook -i inventory.ini show-version.yml --limit sw-lab-01
CheckWhat it can tell youWhat it cannot guarantee
--syntax-checkBasic playbook parsing and syntax validityNetwork reachability or correct live behavior
--list-hostsWhich inventory hosts match the playWhether those targets are safe to modify
--list-tasksTasks selected for executionThe real-world effects of a task
--checkPotential changes for supported modulesA faithful simulation of every module or device
Lab executionBehavior in a representative controlled environmentIdentical behavior in production

Use --limit to narrow the target list, inspect the active inventory, verify the relevant module versions, and maintain a rollback plan before any configuration-changing playbook is approved.

7. Understand idempotency, check mode and secrets

Idempotency

Many declarative modules compare the current and desired state, avoiding repeat changes after the target state is reached. Not every module or playbook behaves that way. Raw command tasks must be reviewed independently.

Check mode

--check can show proposed changes in modules that support it, but unsupported tasks may be skipped or provide incomplete results. It is not a substitute for testing or change approval.

Ansible Vault can encrypt variable files at rest. It does not automatically make console logs, generated backups or decrypted in-memory data secure. Use no_log where appropriate, protect credentials and avoid exposing sensitive diffs to logs. For sensitive configuration tasks, consider turning off diff output.

Operational rule: A generated playbook is a draft for review, not authorization to run commands. Confirm its collection dependencies, credentials, device scope and expected side effects before using it.

8. Use the NetOps Ansible Playbook Generator

The NetOps Ansible Playbook Generator provides a starting point for network configuration backup YAML. On its current page you select a target host or group from inventory and a network OS, then generate YAML to inspect and adapt. The tool helps draft playbook text; it does not connect to switches, validate your credentials or execute the resulting automation.

Network collections are versioned separately from ansible-core. A playbook that references cisco.ios.ios_command needs the corresponding Cisco collection, along with a compatible connection plugin. The exact host variables, commands and connection details depend on the device platform.

IssueLikely causeFirst check
Host pattern did not matchGroup name differs from inventory--list-hosts, inventory spelling
Module or connection not foundRequired collection missing or incompatibleansible-galaxy collection list
Unreachable over SSHPath, port, authentication or host key issueApproved connectivity and SSH policy
Unsupported platformWrong ansible_network_os / pluginPlatform-specific Ansible support
Backup file missingLocal destination, permissions or task failureController path and protected task logs

9. Checklist before automating network infrastructure

Define authorized scopeUse explicit inventory groups, a narrow --limit and least-privilege accounts.
Pin and verify dependenciesReview ansible-core, network collections and platform support.
Read the generated YAMLCheck the hosts, tasks, connection type, return values and potential changes.
Handle credentials correctlyProtect secrets with a vault or approved credential solution.
Test in a representative labInclude syntax, target listing and real device behavior checks.
Keep recoverable backupsEncrypt backups and test restore procedures separately.
Plan production changesFollow maintenance windows, approvals, monitoring and rollback procedures.
Document outcomesRecord what ran, where it ran, and the approved change or job identifier.

Automation reduces repetitive manual effort, but multiplies the impact of incorrect targeting. The most valuable practice is a controlled, reviewable workflow from a small lab to an approved production scope.

10. Frequently asked questions

Is Ansible the same thing as a YAML file?

No. YAML is a data serialization format used to describe playbooks and other configuration files. Ansible is the automation engine and associated ecosystem that interprets playbooks and calls modules.

Do I install Ansible on every network switch?

Typically not. The control node runs Ansible and connects to supported network devices through an appropriate plugin or API. Connectivity, account permissions and device-specific collection support are still required.

Does the NetOps tool run the playbook automatically?

No. The current NetOps generator creates baseline YAML for review. You are responsible for inventory, collections, credentials, testing and controlled execution in your own Ansible environment.

Does --check guarantee no surprises?

No. Check mode does not simulate every possible module action. Modules with limited check-mode support may skip tasks or omit important behavior. Always review and test the playbook in an approved lab.

What is the difference between an inventory and a playbook?

An inventory defines the managed hosts and groups. A playbook declares which of those hosts to target and what ordered tasks to request.

Can network configuration backups expose credentials?

Yes. Some device configurations contain credentials, hashes, keys or sensitive topology details. Restrict access, encrypt backups at rest and avoid sending confidential configuration output to public logs or repositories.

Start with a reviewed YAML baseline

Choose an inventory target and network platform, generate a backup playbook draft, then validate it with your own approved Ansible environment.

Open Ansible Playbook GeneratorExplore Nmap Command GeneratorAll Technical Guides

11. Technical references

  1. Ansible — Playbooks: syntax, execution, idempotency and verification
  2. Ansible — Building and using inventory
  3. Ansible — cisco.ios.ios_command module
  4. Ansible — network_cli connection plugin
  5. Ansible — Check mode and diff mode limitations
  6. Ansible — Vault and sensitive data
  7. IETF RFC 5737 — Documentation-only IPv4 address blocks

Last reviewed: October 27, 2026 · Prepared by: NetOps Tools · Educational content for authorized network administration. Sample IPs and hostnames are documentation examples, not live targets. Collection requirements and device behavior vary by version and vendor. This article does not certify any deployment as safe.