# Infrastructure Automation with Ansible

> Chapter 11 of the Courseiva CISCO-DEVNET-ASSOCIATE curriculum — https://courseiva.com/learn/cisco-devnet-associate/network-automation-tools-ansible

**Official objective:** 2.1 — Describe Ansible concepts, playbooks, and inventory management for network automation

## Introduction

Infrastructure automation with Ansible solves the problem of manually configuring hundreds or thousands of network devices (routers, switches, firewalls) and servers one at a time. For the 200-901 exam, you need to understand how Ansible replaces error-prone manual commands with repeatable, version-controlled automation that executes the same configuration on every device, every time.

## The Restaurant Kitchen Order Analogy

A busy restaurant kitchen on a Saturday night. The head chef has a stack of orders coming in — tables requesting steaks, salads, pastas, each with custom modifications like 'no onions' or 'medium rare'.

Without a system, chaos erupts. The chef scribbles notes on napkins, runs to the fridge to check stock, shouts instructions to the line cooks, and constantly checks if the grill is free. Every new order requires manual intervention — reading the slip, walking to the walk-in cooler, remembering which cook is on which station.

Ansible is like that head chef who, instead of running around, uses a master ordering system. The head chef writes a single set of instructions — a 'playbook' — that says: 'For every steak order, season, grill to medium rare, rest for 3 minutes, plate with herb butter.' A 'play' in the playbook is like one step: 'season the steak.' The 'inventory' is the list of all the kitchen stations — the grill, the sauté station, the salad prep — each with its own capabilities. Ansible connects to each station — each 'managed node' — over a secure network connection (SSH) and executes the instructions without needing a human to run to each station. It doesn't install any permanent software on the stations — it's 'agentless,' like a chef who doesn't need to install a new app on every sous chef's phone to give them orders. If a station is down (the grill is broken), Ansible doesn't just crash — it skips that step and reports the failure. The result: consistent, repeatable, hands-free kitchen operations, every Saturday night.

## Core explanation

Ansible is an open-source automation tool that IT professionals use to configure systems, deploy software, and orchestrate advanced workflows. The core idea is simple: instead of logging into each device individually and typing commands (which takes hours and invites mistakes), you write a single set of instructions that Ansible carries out for you.

At its heart, Ansible is 'agentless.' That means, unlike some other automation tools, you do not need to install any special software — called an 'agent' — on the devices you want to manage. Ansible communicates with them over standard, secure network protocols. For Linux servers, it typically uses SSH (Secure Shell). For network devices like Cisco routers or switches, it uses SSH as well, or sometimes API calls over HTTPS. This makes Ansible very easy to adopt because you don't need to change the devices themselves — they just need to be reachable over the network.

The three foundational concepts in Ansible are:

- Control node: This is the machine where Ansible is installed. It can be your laptop, a dedicated server, or a virtual machine. From here, you write your automation instructions and push them out.
- Managed nodes: These are the devices Ansible configures — the routers, switches, firewalls, servers, cloud instances. They receive and execute the instructions.
- Inventory: A file (usually in INI or YAML format) that lists all your managed nodes. It can group them by function — for example, all 'core-routers,' all 'branch-switches,' all 'web-servers.' You define the inventory once, and Ansible uses it to know which devices to target.

The instructions themselves are written in 'playbooks.' A playbook is a file written in YAML (a human-readable data serialisation language — think of it like a simpler, cleaner version of JSON). A playbook contains one or more 'plays.' Each play targets a specific group of managed nodes (from your inventory) and defines a series of 'tasks' to run on them. Each task calls a single 'module.'

Modules are the actual tools Ansible uses to do work. They are small programs that perform specific actions — for example, the 'ios_config' module applies configuration to a Cisco IOS device; the 'copy' module copies a file; the 'service' module starts or stops a service. Modules are idempotent — this fancy word means running the same module multiple times produces the same result. If a configuration is already in place, the module does nothing new. This prevents accidental duplicates or errors.

Let us walk through a simple real example. Imagine you have ten Cisco switches that all need a new VLAN (Virtual Local Area Network) configured. Without automation, you would SSH into each switch, enter configuration mode, type 'vlan 100', name it, and exit — repeating the exact same process ten times. With Ansible, you write a playbook that looks something like this (in plain language):

- Play: 'Configure VLAN 100 on all switches'
- Target: group 'access-switches' from the inventory
- Tasks:
  - Use the 'ios_vlan' module
  - Provide the vlan_id: 100
  - Provide the name: 'Engineering'

You run the playbook from the control node. Ansible reads the inventory, connects by SSH to each switch in 'access-switches,' executes the module idempotently (only creating the VLAN if it does not already exist), and reports back whether the change was successful on each device. The entire operation takes seconds, and the results are consistent across all ten switches.

What does Ansible replace? It replaces the manual, error-prone process of 'crafting commands' on each device. It also replaces the need to remember the exact syntax for every vendor's operating system — because Ansible modules abstract that away. You tell Ansible 'I want this VLAN' and Ansible knows how to translate that into Cisco, Juniper, or Arista commands.

Why was Ansible created? The creator, Michael DeHaan, wanted a tool that was simpler than existing configuration management tools like Puppet or Chef. Those tools require learning a custom language (like Ruby DSL) and usually need an agent installed. Ansible uses YAML — which is easy to read even for non-programmers — and requires no agents. The philosophy is 'batteries included but swappable' — it ships with hundreds of built-in modules for common tasks.

For the 200-901 exam, you should know that Ansible is declarative in nature — you declare the desired end state (e.g., 'VLAN 100 should exist'), and Ansible makes it so. You should also understand that playbooks are executed in order, top to bottom, and that you can use variables and conditionals to make automation smarter.

In summary, Ansible makes infrastructure automation accessible by using:

- YAML playbooks that are easy to write and read
- An inventory to organise your devices
- Agentless push-based model (control node pushes configs to managed nodes)
- Idempotent modules that do not cause side effects on repetition

This replaces the old 'snowflake' pattern where every device had unique manual configuration, leading to drift and hard-to-debug issues. Instead, you get consistent, repeatable, auditable infrastructure.

## Real-world context

Consider a medium-sized company called 'FinTech Connect' that runs 50 Cisco Catalyst switches across three office floors, plus 20 routers connecting branch offices. The network team receives a security directive: 'Disable Telnet access on all network devices and enable SSH version 2 only.' Doing this manually would require logging into 70 devices, entering enable mode, finding the right configuration lines, typing 'transport input ssh,' and verifying.

A junior network engineer named Maria is assigned the task. She has never used Ansible before but has read the basics. Here is how she would approach it in a real business context:

Maria’s first step is to set up the control node. She installs Ansible on a lightweight Linux virtual machine (VM) in the data centre. She ensures this VM has network access to all 70 devices. She creates an inventory file that groups devices:

- [core-switches] — the 10 main distribution switches
- [access-switches] — the 40 floor switches
- [branch-routers] — the 20 remote routers

She writes a playbook called 'remove-telnet-ssh.yml'. The playbook has two plays. The first play targets all devices in 'core-switches' and 'access-switches' (combined group) and uses the 'ios_config' module with lines to disable telnet and enforce SSH. The second play targets 'branch-routers' and uses the 'ios_config' module with slightly different syntax because those run a different IOS version.

Before running it live, Maria uses the '--check' flag (dry run). This tells Ansible to simulate the changes without actually applying them. The output shows which lines would be changed on each device. She reviews it and catches a mistake — one router group needs an extra line for SSH timeout. She fixes the inventory grouping and re-runs the check.

Confident now, she runs the playbook for real. Within 90 seconds, all 70 devices are updated. Ansible logs the output: 'changed=70, failed=0, unreachable=0'. She saves this as proof of compliance for the auditors.

A month later, a new security policy requires rotating the SSH keys (public/private key pairs used for authentication). Rather than manually generating 70 new key pairs and copying them, Maria writes a new playbook that:

- Generates a new RSA key pair on each device using the 'ios_system' module
- Uses the 'ios_config' module to configure the new key as the active one
- Verifies connectivity using the 'net_ping' module

This entire operation takes 2 minutes and is completely documented in the playbook itself — meaning anyone on the team can repeat it or audit it.

In the real world, IT professionals use Ansible to:

- Apply consistent security baselines across hundreds of devices
- Deploy software updates or firmware upgrades to network hardware
- Automate the provisioning of new branch offices — spin up switches, assign VLANs, set up routing protocols
- Integrate with CI/CD pipelines, where every code change triggers an Ansible run that updates the network to match the new application requirements
- Perform compliance checks — run a playbook daily that checks if any device has Telnet enabled or an outdated OS version, and report deviations

The key insight is that Ansible is not just about speed — it is about reliability and repeatability. A human operator might type a command wrong on one device out of 70. Ansible executes the exact same operations every time. In regulated industries (finance, healthcare), this auditability is often a regulatory requirement.

## Exam focus

The 200-901 exam tests your knowledge of Ansible concepts, playbook structure, and inventory management at a conceptual level — you will not be asked to write a full playbook from scratch, but you must understand the components and how they fit together. The exam is vendor-agnostic in its automation coverage, so focus on general Ansible principles rather than Cisco-specific command syntax.

What they test heavily:

- The three core Ansible components: control node, managed nodes, inventory. You need to know that the control node runs the playbook, the managed nodes are the targets, and the inventory defines the groups.
- Agentless architecture: This is a favourite exam point. Ansible does not require an agent on the managed node — it uses SSH or APIs. Compare this with Puppet (which requires an agent) if a question contrasts the two.
- Playbook structure: You should be able to identify a YAML playbook snippet and know that it contains plays, which contain tasks, which call modules. Know that 'hosts:' defines the target group, 'tasks:' defines the list of actions, and 'name:' is just a human-readable label.
- Idempotency: The exam loves this term. Understanding that running the same playbook twice does not cause duplicate changes unless the configuration has drifted is important.
- Modules: You do not need to memorise hundreds of modules, but you should recognise that 'ios_config', 'ios_command', 'copy', 'service' are common ones. The exam may ask what a specific module does in a multiple-choice question.
- Inventory files: Understand the INI and YAML formats. Know that you can define groups (like '[routers]') and set variables per host or per group.

Traps to watch out for:

- Confusing 'control node' with 'managed node': The control node is where Ansible runs; the managed nodes are the devices it configures. A question might say 'Ansible is installed on the router' — that is wrong unless they are describing a specific edge case.
- Believing Ansible is a programming language: Ansible uses YAML — a data format — not a programming language. It does have loops and conditionals, but it is not Turing-complete like Python.
- Mixing up push vs pull model: Ansible is push-based — the control node sends configs to managed nodes. Puppet is typically pull-based — managed nodes pull configs from a master. This is a classic comparison question.
- Thinking 'idempotent' means 'does nothing': It means 'has the same effect whether run once or multiple times.' The module still checks the state — it just does not repeat changes if the desired state is already achieved.

Concepts to memorise for multiple-choice questions:

- YAML: Used for playbooks and inventory files
- SSH: Default transport for network devices
- Module: The unit of work in Ansible (e.g., ios_config applies configuration lines)
- Playbook: A YAML file containing one or more plays
- Play: A mapping between a host group and the tasks to run on it
- Task: A single call to a module
- Inventory: A file listing managed nodes
- Group: A logical collection of managed nodes (e.g., all routers)
- Variables: Values that can be substituted in playbooks (e.g., {{ vlan_id }})
- Facts: Information Ansible gathers about managed nodes (like OS version, hardware details)

The exam may present you with a scenario: 'A network engineer wants to configure SNMP on 100 routers. Which Ansible approach should they use?' The correct answer is to write a playbook that targets the 'routers' group and uses the 'ios_config' module or a dedicated SNMP module. A trap answer might suggest writing a script in Python to SSH into each one — that is also possible, but the exam is testing knowledge of Ansible as the automation tool.

Finally, be aware that the exam expects you to understand basic troubleshooting: if a playbook fails with 'unreachable,' the control node cannot connect to the managed node — likely a network connectivity issue or wrong IP in the inventory.

## Step by step

1. **Install Ansible on the Control Node** — You first set up a control node — typically a Linux server or a VM. Ansible is installed via package managers like 'apt' or 'yum', or using Python's pip. This machine will be the brain of the operation, sending commands to all managed devices.
2. **Create an Inventory File** — You define an inventory file that lists all your managed nodes — the routers, switches, servers you want to automate. You can group them logically, e.g., [routers] or [branch-switches]. This tells Ansible which devices exist and how to connect to them (IP addresses, SSH credentials).
3. **Write a Playbook in YAML** — You create a text file with a .yml extension. Inside, you define one or more plays. Each play specifies the target group (e.g., routers), and a list of tasks. Each task calls a module (like ios_config) with parameters. This YAML file is your automation blueprint.
4. **Run the Playbook** — You execute the playbook using the 'ansible-playbook' command followed by the filename. Ansible reads the inventory, connects to each managed node in the targeted group via SSH, and executes each task in order. It reports the results: success, failure, or unreachable.
5. **Verify and Iterate** — After the run, you check the output for errors. If a device was unreachable, you troubleshoot connectivity. If a module failed, you adjust the playbook. Ansible supports a '--check' flag for dry runs to preview changes before applying them, allowing safe iteration.

## Comparisons

### Ansible (Push Model) vs Puppet (Pull Model)

**Ansible (Push Model):**
- Control node pushes configuration to managed nodes
- No agent required on managed nodes
- Uses SSH or API for communication

**Puppet (Pull Model):**
- Managed nodes pull configuration from a master server
- Requires an agent installed on each managed node
- Uses its own protocol for communication

### Playbook (YAML) vs Script (e.g., Python or Bash)

**Playbook (YAML):**
- Declarative — describes desired end state
- Idempotent — safe to run repeatedly
- Human-readable, non-programming language

**Script (e.g., Python or Bash):**
- Procedural — describes step-by-step instructions
- Not idempotent — running again may cause duplication
- Requires programming knowledge

### Inventory (INI format) vs Inventory (YAML format)

**Inventory (INI format):**
- Simple key-value file with groups in brackets
- Uses plain text with minimal formatting
- Less flexible for complex variables

**Inventory (YAML format):**
- Uses YAML syntax with nested structures
- Allows more complex variable definitions and hierarchies
- Preferred for larger or more dynamic environments

## Diagram

_This diagram shows how the control node uses the inventory file to target device groups, and how a playbook with multiple plays executes tasks against individual managed nodes._

```mermaid
flowchart TD
    A[Control Node] --> B[Inventory File]
    B --> C[Group: Routers]
    B --> D[Group: Switches]
    A --> E[Playbook: .yml]
    E --> F[Play 1: Configure Routers]
    E --> G[Play 2: Configure Switches]
    F --> H[Task: ios_config module]
    G --> I[Task: ios_vlan module]
    H --> J[Managed Node: Router1]
    H --> K[Managed Node: Router2]
    I --> L[Managed Node: Switch1]
    I --> M[Managed Node: Switch2]
```

## Common misconceptions

- **Misconception:** Ansible requires you to install an agent on every device you want to manage. **Reality:** Ansible is agentless — it communicates over SSH or APIs without needing any extra software on the managed device. (Many beginners come from tools like Puppet or Chef which do require agents. The word 'agentless' is a key differentiator and is often misunderstood.)
- **Misconception:** Ansible playbooks are written in Python. **Reality:** Ansible playbooks are written in YAML — a human-readable data serialisation language. Python is used for writing custom modules, but playbooks themselves are YAML. (Beginners see 'Ansible is written in Python' and assume they must write Python. The exam tests recognition of YAML for playbooks.)
- **Misconception:** Ansible only works for Linux servers, not network devices. **Reality:** Ansible works with any device that supports SSH or an API — including Cisco routers, switches, firewalls, and many other vendors' networking gear. (The exam's network automation focus confuses learners who associate Ansible only with server configuration. Modules like 'ios_config' are network-specific.)
- **Misconception:** Once you run an Ansible playbook, it permanently changes the device's configuration and you cannot reverse it. **Reality:** Ansible applies changes based on what the playbook says. You can write a separate playbook to revert changes, and because playbooks are text files, you can use version control (like Git) to track and roll back. (This misconception comes from fear of automation breaking things. The exam tests understanding that playbooks are controllable and reversible, not one-way.)
- **Misconception:** Ansible is useless if you only have a few devices — you must manually configure them anyway. **Reality:** Even with a few devices, Ansible saves time by ensuring consistency and providing an auditable record of changes. It also reduces human error, which is valuable regardless of scale. (Beginners think automation is only for large scale. The exam tests the principle that automation improves reliability at any scale.)

## Key takeaways

- Ansible is agentless — it does not require any software installed on managed nodes, only SSH or API access.
- Playbooks are written in YAML and contain one or more plays, each targeting a group of hosts from the inventory.
- Modules are idempotent — running the same task multiple times produces the same result without causing unintended changes.
- The control node is the machine where Ansible is installed and from which playbooks are executed; managed nodes are the devices being configured.
- Inventory files organise managed nodes into groups (e.g., routers, switches) and allow setting variables per host or group.
- Ansible uses a push model — the control node pushes configuration to managed nodes, unlike tools like Puppet that use a pull model.
- Idempotency is the property that ensures consistent state: if a device already has the desired configuration, the module makes no changes.
- Playbooks are executed sequentially from top to bottom, and each task is run against all hosts in the targeted group before moving to the next task.

## FAQ

**Do I need to know programming to use Ansible?**

No, you do not need to be a programmer. Playbooks are written in YAML, which is a simple data format designed to be readable. You just need to understand basic concepts like lists and dictionaries.

**Can Ansible configure both Cisco devices and Windows servers?**

Yes, Ansible can manage any device that supports SSH (for Linux and network gear) or WinRM (for Windows). There are specific modules for each platform, like ios_config for Cisco and win_feature for Windows.

**What is the difference between a playbook and a module?**

A playbook is the overall automation script containing plays and tasks. A module is the individual tool that performs a specific action, like configuring a VLAN or copying a file. A playbook calls modules to do the work.

**How does Ansible handle passwords and credentials securely?**

You can use Ansible Vault to encrypt sensitive data like passwords directly in the playbook or inventory file. You can also pass credentials via environment variables or use SSH keys instead of passwords.

**What does 'idempotent' mean in Ansible?**

Idempotent means that running the same module multiple times will always bring the system to the same desired state. If the state is already correct, the module makes no changes. This prevents accidental duplication or errors.

**Can I use Ansible to automatically revert a bad configuration?**

Ansible does not have a built-in rollback feature, but you can write a separate playbook that applies a known-good configuration. Using version control for your playbooks allows you to revert to an earlier version and reapply it.

## Check your understanding

1. **What is the term for Ansible's ability to produce the same result when a playbook is run multiple times?**

   Answer: Idempotency — Ansible modules check the current state and only make changes if the desired state is not already present.

2. **In which format are Ansible playbooks written?**

   Answer: YAML (Yet Another Markup Language) — a human-readable data serialisation format.

3. **Does Ansible require an agent on the managed node to communicate?**

   Answer: No, Ansible is agentless and uses SSH or APIs to communicate with managed nodes.

4. **What is the role of the control node in Ansible?**

   Answer: The control node is the machine where Ansible is installed and from which playbooks are executed against managed nodes.

5. **Name one Cisco-specific Ansible module that applies configuration to IOS devices.**

   Answer: ios_config — this module is used to apply configuration lines to Cisco IOS devices.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/cisco-devnet-associate/network-automation-tools-ansible
