<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>Ansible 101 for networking · Network Doodles</title><link>https://networkdoodles.com/lessons/ansible-101/</link><description>Ansible from zero for network engineers: inventory, playbooks, variables, loops and templates, handlers, roles, vault, and running it like production. Eight lessons, each with a hands-on lab chapter on real switches running CapeOS.</description><language>en-us</language><managingEditor>David Henderson</managingEditor><lastBuildDate>Mon, 16 Nov 2026 09:00:00 -0500</lastBuildDate><atom:link href="https://networkdoodles.com/lessons/ansible-101/index.xml" rel="self" type="application/rss+xml"/><item><title>Execution Environments, ansible-lint and CI for Network Playbooks (Ansible 101 for Networking, Lesson 8)</title><link>https://networkdoodles.com/lessons/ansible-101/production/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/production/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>ansible-navigator</category><category>ci-cd</category><category>howto</category><description>Package Ansible and its collections into an execution environment, run playbooks with ansible-navigator, pass ansible-lint production rules, and gate it in CI.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Over seven lessons the lab went from one ad-hoc command to roles, variables, handlers and a vaulted password.
It all runs from a Python virtual environment in your codespace. That&rsquo;s fine for learning. It isn&rsquo;t how
production should run it, for one boring and important reason: <strong>&ldquo;works on my machine&rdquo; isn&rsquo;t a deployment
strategy.</strong></p>
<p>This last lesson closes that gap with three tools: an <strong>execution environment</strong> so every run uses exactly the
same Ansible, <strong>ansible-lint</strong> so the code meets a standard before anyone reviews it, and a <strong>CI pipeline</strong> so
both happen on every push without anyone remembering to.</p>
<hr>
<h2 id="the-problem-with-pip-install-ansible">The problem with &ldquo;pip install ansible&rdquo;</h2>
<p>Your laptop has ansible-core 2.20.1 and cisco.ios 11.6.0. Your colleague installed a few months earlier and
has older versions of both. The CI runner has whatever was newest when its image was built. The automation server has something else again. Every one of
them runs the same playbook slightly differently, and the differences show up as bugs nobody can reproduce.</p>
<p>An <strong>execution environment</strong> (EE) fixes that by putting Ansible itself in a container:</p>
<ul>
<li>ansible-core, pinned</li>
<li>the collections from <code>requirements.yml</code>, pinned</li>
<li>their Python dependencies</li>
<li>any system packages they need</li>
</ul>
<p>Build it once, tag it, and everything that runs your playbooks (your laptop, CI, Ansible Automation Platform)
uses that same image. If it works in the EE on your machine, it works in the EE everywhere.</p>

<figure class="netsim" data-netsim tabindex="0" aria-label="The same playbook on a laptop, a colleague&#39;s machine and a CI runner with different Ansible versions; an execution environment image pins them so all three runs match; then ansible-lint as the gate before review, on every push. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="The same playbook on a laptop, a colleague&#39;s machine and a CI runner with different Ansible versions; an execution environment image pins them so all three runs match; then ansible-lint as the gate before review, on every push"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":340,"links":[],"narrow":{"at":{"ci":[90,400],"col":[90,290],"ee":[265,290,180],"lap":[90,180],"lint":[250,60,190],"pb":[80,60]},"h":470,"w":360},"nodes":{"ci":{"kind":"ci","label":"CI runner","sub":"whatever was newest","x":390,"y":275},"col":{"kind":"laptop","label":"A colleague","sub":"older versions","x":390,"y":165},"ee":{"c":"green","h":44,"hidden":true,"kind":"box","label":"ans101-ee:1","sub":"execution environment","w":190,"x":640,"y":165},"lap":{"kind":"laptop","label":"Your laptop","sub":"core 2.20.1, ios 11.6.0","x":390,"y":55},"lint":{"h":44,"hidden":true,"kind":"box","label":"ansible-lint","sub":"profile: production","w":190,"x":110,"y":280},"pb":{"kind":"file","label":"site.yml","sub":"same playbook","x":90,"y":120}},"steps":[{"hot":["lap","col","ci"],"packets":[{"label":"site.yml","path":["pb","lap"]},{"label":"site.yml","path":["pb","col"]},{"label":"site.yml","path":["pb","ci"]}],"table":{"cols":["machine","Ansible and collections","result"],"rows":[["your laptop","ansible-core 2.20.1, cisco.ios 11.6.0","its own"],["a colleague","older versions of both","its own"],["CI runner","whatever was newest when its image was built","its own"]],"title":"who runs site.yml"},"text":"Each one installed Ansible at a different time, so each runs the same YAML on a different engine and modules.","title":"One playbook, three machines."},{"bad":["col","ci"],"say":{"col":"works on my machine"},"sayAt":{"col":{"narrow":"right","wide":"right"}},"text":"Every one of them runs the playbook slightly differently, and \"works on my machine\" isn't a deployment strategy.","title":"Bugs nobody can reproduce."},{"code":{"hl":[2,5],"lines":["dependencies:","  ansible_core:","    package_pip: ansible-core==2.20.1","  python:","    - ansible-pylibssh==1.4.0","  galaxy: requirements.yml"],"title":"execution-environment.yml"},"hot":["ee"],"show":["ee"],"text":"ansible-core, the collections from `requirements.yml` and their Python dependencies, in one container image.","title":"The EE image pins them."},{"good":["lap","col","ci"],"hot":["ee"],"packets":[{"c":"green","label":"ans101-ee:1","path":["ee","lap"]},{"c":"green","label":"ans101-ee:1","path":["ee","col"]},{"c":"green","label":"ans101-ee:1","path":["ee","ci"]}],"set":{"ci":"ans101-ee:1","col":"ans101-ee:1","lap":"ans101-ee:1"},"table":{"cols":["machine","Ansible and collections","result"],"rows":[["your laptop","ans101-ee:1","same"],["a colleague","ans101-ee:1","same"],["CI runner","ans101-ee:1","same"]],"title":"who runs site.yml"},"text":"`ansible-navigator` runs the playbook in a fresh container from `ans101-ee:1`. Same image, same run, everywhere.","title":"All three run the same image."},{"bad":["lint"],"code":{"lines":["name[play]: All plays should be named.","playbooks/legacy.yml:6:3","","fqcn[action-core]: Use FQCN for builtin module actions (debug).","playbooks/legacy.yml:15:5"],"title":"ansible-lint"},"packets":[{"c":"red","end":"drop","label":"legacy.yml","path":["pb","lint"]}],"show":["lint"],"text":"ansible-lint reads the playbook first. The legacy one runs fine and still fails: no play names, `debug` without its full name.","title":"Lint before a reviewer."},{"code":{"lines":["lint:","  script:","    - yamllint .","    - ansible-lint --offline","","syntax:","  script:","    - ansible-playbook playbooks/site.yml --syntax-check"],"title":".gitlab-ci.yml"},"good":["lint"],"hot":["ci"],"packets":[{"c":"green","label":"push","path":["pb","lint"]}],"text":"CI runs yamllint, ansible-lint and a syntax check of the whole site. A reviewer's time goes on the change itself.","title":"On every push, before review."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<hr>
<h2 id="building-an-ee">Building an EE</h2>
<p>The definition is a short YAML file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># execution-environment.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">version</span><span class="p">:</span><span class="w"> </span><span class="m">3</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">images</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">base_image</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">quay.io/fedora/fedora-minimal:43</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">dependencies</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">python_interpreter</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">package_system</span><span class="p">:</span><span class="w"> </span><span class="l">python3</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">python_path</span><span class="p">:</span><span class="w"> </span><span class="l">/usr/bin/python3</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">ansible_core</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">package_pip</span><span class="p">:</span><span class="w"> </span><span class="l">ansible-core==2.20.1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">ansible_runner</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">package_pip</span><span class="p">:</span><span class="w"> </span><span class="l">ansible-runner==2.4.3</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">python</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">ansible-pylibssh==1.4.0</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">galaxy</span><span class="p">:</span><span class="w"> </span><span class="l">requirements.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">options</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">package_manager_path</span><span class="p">:</span><span class="w"> </span><span class="l">/usr/bin/dnf5</span><span class="w">
</span></span></span></code></pre></div><p>The line that matters most is <code>galaxy: requirements.yml</code>. The EE installs the <strong>same pinned collections</strong> the
venv uses, from the same file. One source of truth, two ways to run.</p>
<p>The <code>python:</code> list is the one people forget. Collections bring modules, but some of what they need is plain
Python underneath: <code>network_cli</code> holds its SSH sessions through a library, <code>ansible-pylibssh</code>, that isn&rsquo;t
part of ansible-core. Leave it out and the image builds fine, then fails the first time it talks to a switch.</p>
<p>Build it with <strong>ansible-builder</strong>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">ansible-builder build --tag ans101-ee:1 --file execution-environment.yml
</span></span></code></pre></div><p>ansible-builder generates a Containerfile and builds it. A note from building the lab: Red Hat&rsquo;s and the
community&rsquo;s EE base images were x86-only when I tried them, which fails on Apple Silicon. A multi-arch base
like <code>fedora-minimal</code> builds natively everywhere. Check your base image&rsquo;s architectures before you standardise
on it.</p>
<hr>
<h2 id="running-playbooks-with-ansible-navigator">Running playbooks with ansible-navigator</h2>
<p><strong>ansible-navigator</strong> is the front end that runs playbooks <em>inside</em> the EE. Its settings live next to
<code>ansible.cfg</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># ansible-navigator.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible-navigator</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">mode</span><span class="p">:</span><span class="w"> </span><span class="l">stdout</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">execution-environment</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">image</span><span class="p">:</span><span class="w"> </span><span class="l">ans101-ee:1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">pull</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">policy</span><span class="p">:</span><span class="w"> </span><span class="l">never           </span><span class="w"> </span><span class="c"># built locally, never pulled</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">container-options</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">&#34;--network=ans101-mgmt&#34;</span><span class="p">]</span><span class="w">
</span></span></span></code></pre></div><p>Then it&rsquo;s almost the command you know:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">ansible-navigator run playbooks/site.yml
</span></span></code></pre></div><p>The output is the same PLAY RECAP you&rsquo;ve been reading since lesson 2. What&rsquo;s different is everything underneath:
the playbook ran in a fresh container from a known image, with nothing from your machine except the project
folder.</p>
<p>That <code>container-options</code> line is the one that&rsquo;ll bite you. The EE is a container, so it&rsquo;s on its own network,
and it can&rsquo;t see the switches. Joining it to the switches&rsquo; management network fixes that. In production the
equivalent question is &ldquo;can the EE reach the devices from where it runs?&rdquo;, and it&rsquo;s always worth asking before
the first run, not after.</p>
<p>Drop <code>mode: stdout</code> and navigator opens an interactive TUI instead, where you can step through every play,
task and host result. It&rsquo;s the best way I know to dig into a failed run.</p>
<hr>
<h2 id="ansible-lint-a-standard-before-a-reviewer">ansible-lint: a standard before a reviewer</h2>
<p><strong>ansible-lint</strong> reads your playbooks and roles and tells you what&rsquo;s wrong, from outright bugs to style. The lab
runs it with the strictest built-in profile:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># .ansible-lint</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">profile</span><span class="p">:</span><span class="w"> </span><span class="l">production</span><span class="w">
</span></span></span></code></pre></div><p>Here&rsquo;s the lab&rsquo;s &ldquo;legacy&rdquo; playbook, written the way a lot of real ones are:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl">- <span class="nt">hosts</span><span class="p">:</span><span class="w"> </span><span class="l">fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">gather_facts</span><span class="p">:</span><span class="w"> </span><span class="kc">no</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">tasks</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">cisco.ios.ios_command</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">commands</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span>- <span class="l">show version</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">register</span><span class="p">:</span><span class="w"> </span><span class="l">Version</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">debug</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">msg</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{inventory_hostname}}: {{ Version.stdout_lines[0][0] }}&#34;</span><span class="w">
</span></span></span></code></pre></div><p>It runs fine. ansible-lint still has a list of complaints, each with a rule name and a line number:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">name[play]: All plays should be named.
</span></span><span class="line"><span class="cl">playbooks/legacy.yml:6:3
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">fqcn[action-core]: Use FQCN for builtin module actions (debug).
</span></span><span class="line"><span class="cl">playbooks/legacy.yml:15:5
</span></span></code></pre></div><p>Between them, the findings cover:</p>
<ul>
<li><strong>No play or task names.</strong> Your output and logs say which module ran, not what happened.</li>
<li><strong><code>debug</code> instead of <code>ansible.builtin.debug</code>.</strong> Fully qualified names say exactly which collection you mean.</li>
<li><strong><code>no</code> instead of <code>false</code>.</strong> YAML 1.1 truthiness is a trap; be explicit.</li>
<li><strong><code>Version</code> with a capital.</strong> Variable names are lowercase by convention, and some tools care.</li>
<li><strong><code>{{inventory_hostname}}</code> with no spaces.</strong> Style, but consistent style is what makes review fast.</li>
<li><strong>Indentation</strong> that YAML accepts and humans misread.</li>
</ul>
<p>Building the lab, ansible-lint also caught my own roles: unprefixed role variables (the reason for <code>base_</code>
in lesson 6) and a template path that climbed out of the playbook folder with <code>../</code>. Both worked; both were the
kind of thing that becomes a bug later. That&rsquo;s what lint is for.</p>
<p>Two rules for living with it:</p>
<ol>
<li><strong>Fix, don&rsquo;t silence.</strong> Every rule can be skipped with a comment. Each skip should have a reason you&rsquo;d
defend in review.</li>
<li><strong>Run it before review, not in review.</strong> A reviewer&rsquo;s time is for &ldquo;is this the right change&rdquo;, not &ldquo;you
forgot a task name&rdquo;.</li>
</ol>
<hr>
<h2 id="ci-so-nobody-has-to-remember">CI: so nobody has to remember</h2>
<p>The last piece runs all of that automatically. The lab&rsquo;s <code>.gitlab-ci.yml</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nt">default</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">image</span><span class="p">:</span><span class="w"> </span><span class="l">python:3.13-slim</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">before_script</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">echo &#34;${VAULT_PASSWORD:-not-needed-for-lint}&#34; &gt; .vault-pass</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">pip install -q -r requirements.txt</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">ansible-galaxy collection install -r requirements.yml &gt; /dev/null</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">lint</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">script</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">yamllint .</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">ansible-lint --offline</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">syntax</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">script</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">ansible-playbook playbooks/site.yml --syntax-check</span><span class="w">
</span></span></span></code></pre></div><p>Every push now gets YAML style, Ansible lint and a syntax check of the whole site. A merge request can&rsquo;t
quietly introduce an unnamed task or a broken role.</p>
<h3 id="where-ci-gets-the-vault-key">Where CI gets the vault key</h3>
<p>Lesson 7 left <code>ansible.cfg</code> pointing at <code>.vault-pass</code>, a file that is never committed. A CI job starts from a
fresh clone, so the file isn&rsquo;t there. The first line of <code>before_script</code> recreates it at the start of every
job, from a CI/CD variable called <code>VAULT_PASSWORD</code>. In GitLab you set that under <em>Settings → CI/CD →
Variables</em> and mark it <strong>masked</strong>, so it never appears in a job log. The key lives in the CI system&rsquo;s secret
store, the job writes it to a file for the length of the run, and the container is thrown away afterwards.</p>
<p>The lab&rsquo;s jobs only lint and syntax-check, which never decrypt anything, so a placeholder is enough when the
variable isn&rsquo;t set. A job that runs playbooks against devices needs the real one.</p>
<p>Notice what CI <em>doesn&rsquo;t</em> do: talk to the switches. GitLab&rsquo;s runners can&rsquo;t reach a lab in your codespace, and in
production you&rsquo;d think hard before giving a shared runner device credentials. The pattern that scales is CI for
everything that can be checked without the network (lint, syntax, schema, templates rendered to files), then a
deploy step that runs check mode against real devices from somewhere that&rsquo;s allowed to reach them, and
finally the real run, gated by a human. That&rsquo;s the <span class="link-soon">GitOps course</span>, next.</p>
<hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-an-ee-nobody-rebuilds">1. An EE nobody rebuilds</h3>
<p>An EE built once in 2024 and never touched is just a different flavour of &ldquo;works on my machine&rdquo;. Rebuild it
when <code>requirements.yml</code> changes, tag it with a version, and keep its definition in the same repo as the
playbooks.</p>
<h3 id="2-latest">2. <code>latest</code></h3>
<p><code>image: my-ee:latest</code> means today&rsquo;s run and tomorrow&rsquo;s run may use different Ansible. Tag EEs with versions and
pin them in <code>ansible-navigator.yml</code>, exactly like collections.</p>
<h3 id="3-lint-that-only-runs-on-laptops">3. Lint that only runs on laptops</h3>
<p>If lint isn&rsquo;t in CI, it&rsquo;s a suggestion. Put it in the pipeline from day one, while the codebase is small enough
to make clean.</p>
<h3 id="4-a-pipeline-with-device-credentials">4. A pipeline with device credentials</h3>
<p>The fastest way to turn a CI compromise into a network compromise. Keep device access in a dedicated, audited
place (AAP, or a locked-down runner), and keep the shared pipeline to the checks that don&rsquo;t need it.</p>
<hr>
<h2 id="you-did-it">You did it</h2>
<p>That&rsquo;s Ansible 101 for networking. Eight lessons ago this was an inventory file and an ad-hoc command. Now it&rsquo;s
two roles with defaults and handlers, configuring a leaf-spine fabric from data, with a vaulted password,
running in an execution environment, lint-clean, with a pipeline. That&rsquo;s not a toy. That&rsquo;s the structure real
network automation teams use.</p>
<p><a href="/labs/ansible-101/#chapter-8">Chapter 8 of the lab</a> builds the EE and runs <code>site.yml</code> in it, cleans up the
legacy playbook until ansible-lint passes, and adds the lint and syntax jobs to the pipeline.</p>
<p>Where next? The <span class="link-soon">GitOps for networks</span> course takes this repo and puts it behind
merge requests, reviews and a deploy pipeline. And the <span class="link-soon">NetBox course</span> replaces the
inventory files with NetBox as your source of truth.</p>
]]></content:encoded></item><item><title>Ansible Vault for Network Device Passwords (Ansible 101 for Networking, Lesson 7)</title><link>https://networkdoodles.com/lessons/ansible-101/secrets/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/secrets/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>security</category><category>ansible-vault</category><category>howto</category><description>Get the switch password out of plain text with ansible-vault: what to encrypt, the vault_ variable pattern, keeping the vault key out of Git, and its limits.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Since <a href="/lessons/ansible-101/hello-ansible/">lesson 1</a> the lab&rsquo;s switch password has been sitting in a YAML file in
plain text, with a comment promising that lesson 7 would fix it. This is lesson 7.</p>
<p>I&rsquo;ve written before about <a href="/posts/donthardcodepasswords/">why you shouldn&rsquo;t hardcode passwords</a>. This post is
the practical Ansible version: <strong>ansible-vault</strong>, the pattern that keeps vaulted files readable, and the one
file that must never reach Git.</p>
<hr>
<h2 id="the-problem-precisely">The problem, precisely</h2>
<p>Right now <code>inventory/group_vars/fabric.yml</code> contains:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nt">ansible_user</span><span class="p">:</span><span class="w"> </span><span class="l">admin</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible_password</span><span class="p">:</span><span class="w"> </span><span class="l">capeos-lab</span><span class="w">
</span></span></span></code></pre></div><p>Commit that and the password is in Git forever. Not until you delete the line: forever. It&rsquo;s in the history,
in every clone, in every fork, in the CI cache. Rotating the password is the only real fix, and on a network
that&rsquo;s every device.</p>
<p>We want three things:</p>
<ol>
<li>The password is <strong>in Git</strong>, so the repo is still the complete description of the network.</li>
<li>It&rsquo;s <strong>unreadable</strong> to anyone without the key.</li>
<li>The <strong>key is not in Git</strong>.</li>
</ol>
<hr>
<h2 id="how-ansible-vault-works">How ansible-vault works</h2>
<p>ansible-vault encrypts files (or single values) with AES-256 using a password you choose, the <strong>vault
password</strong>. Ansible decrypts them in memory when it runs; they never touch disk in clear text. An encrypted
file looks like this, and it&rsquo;s safe to commit:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">$ANSIBLE_VAULT;1.1;AES256
</span></span><span class="line"><span class="cl">32653236363634656263313066396265613937616133336430353330393338626165333766383163
</span></span><span class="line"><span class="cl">3836373465373031333334333465393337376132646438390a616132313762633532636561363561
</span></span><span class="line"><span class="cl">...
</span></span></code></pre></div><p>The setup has a handful of moving parts, and each has one job:</p>
<table>
  <thead>
      <tr>
          <th>Piece</th>
          <th>What it&rsquo;s for</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><code>.vault-pass</code></td>
          <td>A file holding the vault password: the key. It stays on your machine, readable only by you (<code>chmod 600</code>), and never in Git.</td>
      </tr>
      <tr>
          <td><code>.gitignore</code> entry for <code>.vault-pass</code></td>
          <td>Makes sure the key can&rsquo;t be committed by accident. Add it <em>before</em> the file exists.</td>
      </tr>
      <tr>
          <td><code>vault_password_file = .vault-pass</code> in <code>ansible.cfg</code></td>
          <td>Tells Ansible where the key is, so every run decrypts without asking.</td>
      </tr>
      <tr>
          <td><code>ansible-vault create</code></td>
          <td>Makes a new encrypted file and opens it in your editor.</td>
      </tr>
      <tr>
          <td><code>ansible-vault view</code> / <code>edit</code></td>
          <td>Reads or changes an encrypted file without ever writing the clear text to disk.</td>
      </tr>
      <tr>
          <td><code>ansible-vault rekey</code></td>
          <td>Re-encrypts a file with a new vault password, for when the key itself has to change.</td>
      </tr>
      <tr>
          <td><code>ansible-vault encrypt_string</code></td>
          <td>Encrypts one value, for pasting into an otherwise plain YAML file.</td>
      </tr>
  </tbody>
</table>
<p>That <code>.gitignore</code> line is the most important line in this post. Everything else is recoverable; a committed
key isn&rsquo;t.</p>
<h3 id="a-whole-file-or-one-value">A whole file, or one value</h3>
<p>There are two ways to encrypt, and they suit different secrets.</p>
<p><strong>A whole file</strong> (<code>ansible-vault create</code>) is the simple one. <code>view</code>, <code>edit</code> and <code>rekey</code> all work on it, and
you can keep several secrets in it. The cost is that everything in the file is hidden, from reviewers as much
as from attackers.</p>
<p><strong>One value</strong> (<code>ansible-vault encrypt_string</code>) encrypts a single string and prints a block you paste into a
normal file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nt">snmp_community</span><span class="p">:</span><span class="w"> </span>!<span class="l">vault |</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="l">$ANSIBLE_VAULT;1.1;AES256</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="m">66383430653433353434623339646165323662353563666433656536636265656363663036313434</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="l">...</span><span class="w">
</span></span></span></code></pre></div><p>The rest of the file stays readable, and the variable name stays visible, so a diff shows <em>that</em> the
community changed even though nobody can see what to. The cost: each value is encrypted on its own, so you
can&rsquo;t <code>view</code> or <code>edit</code> it in place; changing it means encrypting a new value and pasting it over the old one.</p>
<p>Rule of thumb: inline for the odd value that lives naturally in a plain settings file, a vault file once you
have more than a couple of secrets, or any you&rsquo;ll change often.</p>
<hr>
<h2 id="the-vault_-pattern">The <code>vault_</code> pattern</h2>
<p>Here&rsquo;s the mistake almost everyone makes first: encrypting <code>group_vars/fabric.yml</code> whole. It works, and now
nobody can see <em>any</em> of the fabric&rsquo;s settings without the key, not the connection type, not the NTP servers,
nothing. Code review on that file becomes &ldquo;trust me&rdquo;.</p>
<p>The pattern that fixes it is small:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># inventory/group_vars/all/vault.yml   (encrypted)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">vault_ansible_password</span><span class="p">:</span><span class="w"> </span><span class="l">capeos-lab</span><span class="w">
</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># inventory/group_vars/fabric.yml     (plain text)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible_user</span><span class="p">:</span><span class="w"> </span><span class="l">admin</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible_password</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ vault_ansible_password }}&#34;</span><span class="w">   </span><span class="c"># from inventory/group_vars/all/vault.yml</span><span class="w">
</span></span></span></code></pre></div><ul>
<li>The <strong>encrypted file holds only secrets</strong>, each named with a <code>vault_</code> prefix.</li>
<li>The <strong>plain file references them</strong>, so anyone can read the fabric&rsquo;s settings, search for where the
password is used, and review changes, without the key.</li>
</ul>
<p><code>group_vars/all/</code> is a folder rather than a file: Ansible loads every file inside a group&rsquo;s folder, which lets
you keep <code>vault.yml</code> separate from the plain settings for the same group.</p>
<p>The playbooks don&rsquo;t change at all. Ansible finds the key through <code>ansible.cfg</code>, decrypts in memory, and the
switches never know anything changed.</p>

<figure class="netsim" data-netsim tabindex="0" aria-label="Where the vault password lives: the vault file in Git is ciphertext, the key file stays on your machine and is gitignored, at run time Ansible decrypts in memory and logs in to the switch, a clone of the repo gets only ciphertext, and CI writes the key from a masked variable. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="Where the vault password lives: the vault file in Git is ciphertext, the key file stays on your machine and is gitignored, at run time Ansible decrypts in memory and logs in to the switch, a clone of the repo gets only ciphertext, and CI writes the key from a masked variable"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":340,"links":[],"narrow":{"at":{"ans":[270,230],"ci":[80,380],"clone":[80,230],"key":[270,70],"leaf1":[270,380],"repo":[80,70]},"h":440,"w":360},"nodes":{"ans":{"kind":"gear","label":"ansible-playbook","sub":"on your machine","x":360,"y":250},"ci":{"hidden":true,"kind":"ci","label":"CI job","sub":"VAULT_PASSWORD, masked","x":640,"y":80},"clone":{"hidden":true,"kind":"laptop","label":"A clone","sub":"no .vault-pass","x":110,"y":250},"key":{"kind":"file","label":".vault-pass","sub":"your machine only","x":360,"y":80},"leaf1":{"kind":"switch","label":"leaf1","sub":"login: admin","x":640,"y":250},"repo":{"kind":"repo","label":"Git repo","sub":"vault.yml: ciphertext","x":110,"y":80}},"steps":[{"code":{"lines":["$ANSIBLE_VAULT;1.1;AES256","32653236363634656263313066396265613937616133336430353330393338626165333766383163","3836373465373031333334333465393337376132646438390a616132313762633532636561363561","..."],"title":"inventory/group_vars/all/vault.yml"},"hot":["repo"],"text":"`group_vars/all/vault.yml` is AES-256 ciphertext. Safe to commit: without the key, it's noise.","title":"In Git, the vault file is ciphertext."},{"code":{"hl":[1],"lines":["ansible_user: admin","ansible_password: \"{{ vault_ansible_password }}\""],"title":"inventory/group_vars/fabric.yml"},"hot":["repo"],"text":"`fabric.yml` stays readable. Reviewers can see where the password is used without seeing it.","title":"The plain file only names the secret."},{"code":{"hl":[1],"lines":["# .gitignore",".vault-pass","","# ansible.cfg","vault_password_file = .vault-pass"],"title":"two lines that keep it out"},"hot":["key"],"packets":[{"c":"red","end":"drop","label":"git add","path":["key","repo"]}],"say":{"key":"gitignored,\nchmod 600"},"sayAt":{"key":{"narrow":"below","wide":"right"}},"text":"`.vault-pass` holds the vault password. `.gitignore` lists it, so it can't be committed by accident.","title":"The key stays on your machine."},{"hot":["ans"],"packets":[{"label":"ciphertext","path":["repo","ans"]},{"label":"key","path":["key","ans"]}],"say":{"ans":"decrypted in memory,\nnever on disk"},"sayAt":{"ans":{"narrow":"below","wide":"right"}},"text":"Ansible reads the ciphertext and the key, and decrypts the value in memory. The clear text never touches disk.","title":"At run time, decrypted in memory."},{"code":null,"good":["leaf1"],"packets":[{"c":"green","label":"SSH login","path":["ans","leaf1"]}],"text":"Ansible logs in to leaf1 as `admin` with the decrypted password. The switch never knows a vault was involved.","title":"The switch just sees a login."},{"bad":["clone"],"packets":[{"label":"git clone","path":["repo","clone"]}],"say":{"clone":"ciphertext,\nno key"},"sayAt":{"clone":{"narrow":"right","wide":"right"}},"show":["clone"],"text":"Anyone who clones the repo has `vault.yml` but no key. Without `.vault-pass`, the password stays unreadable.","title":"A clone gets only ciphertext."},{"code":{"hl":[1],"lines":["before_script:","  - echo \"${VAULT_PASSWORD:-not-needed-for-lint}\" \u003e .vault-pass"],"title":".gitlab-ci.yml"},"hot":["ci"],"packets":[{"label":"fresh clone","path":["repo","ci"]}],"show":["ci"],"text":"A job starts from a fresh clone, writes `.vault-pass` from `VAULT_PASSWORD`, and the container is thrown away afterwards.","title":"CI writes the key from a masked variable."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<hr>
<h2 id="checking-you-actually-fixed-it">Checking you actually fixed it</h2>
<p>Encrypting the file you were looking at isn&rsquo;t the same as getting the password out of the repo. Search every
<strong>tracked</strong> file for the old password, not just the one you edited, because it tends to turn up in a README,
a test script or an example inventory somebody copied. <code>git grep</code> does exactly that: it searches what Git
would commit, and nothing else.</p>
<p>Expect some hits you meant. A lab&rsquo;s README that documents the login on purpose is fine. Anything you&rsquo;d copy
into production isn&rsquo;t.</p>
<p>And if the password was <em>ever</em> committed in clear text, assume it&rsquo;s compromised and rotate it. Removing it
from the latest commit doesn&rsquo;t remove it from history.</p>
<hr>
<h2 id="where-vault-stops-being-enough">Where vault stops being enough</h2>
<p>ansible-vault is the right first step, and for a lab or a small team it might be all you need. It has limits
worth knowing before you outgrow it:</p>
<ul>
<li><strong>One key unlocks everything.</strong> Everyone who can run the playbooks can read every secret. Vault IDs (separate
keys per environment) help a little.</li>
<li><strong>Rotation is manual.</strong> Change a device password and someone has to edit, re-encrypt and commit.</li>
<li><strong>The key still has to live somewhere.</strong> On a laptop it&rsquo;s a file; in CI it&rsquo;s a masked variable. Either way,
it&rsquo;s a long-lived secret protecting other secrets.</li>
</ul>
<p>The next step is a <strong>secrets manager</strong>: HashiCorp Vault, CyberArk, AWS Secrets Manager, Azure Key Vault. Ansible
fetches secrets at runtime through a lookup plugin, nothing sensitive is stored in Git at all, and access is
per person or per pipeline, audited and revocable. If you run Ansible Automation Platform, its credential store
does the same job and keeps secrets out of the playbook&rsquo;s reach entirely.</p>
<p>The playbooks don&rsquo;t change much when you move: <code>ansible_password</code> just gets its value from a lookup instead
of a <code>vault_</code> variable. That&rsquo;s another reason the <code>vault_</code> pattern pays off. The plain files never cared where
the value came from.</p>
<hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-committing-the-key-next-to-the-lock">1. Committing the key next to the lock</h3>
<p><code>.vault-pass</code> in the repo, or the vault password in the README, or <code>echo</code> in a committed script. All three
undo the encryption. The key lives outside Git, always.</p>
<h3 id="2-encrypting-everything">2. Encrypting everything</h3>
<p>A fully encrypted <code>group_vars</code> file can&rsquo;t be reviewed, diffed or searched. Encrypt secrets only, with the
<code>vault_</code> pattern.</p>
<h3 id="3-printing-secrets">3. Printing secrets</h3>
<p><code>debug: var=ansible_password</code> prints it decrypted, straight into your CI log. Any task that handles a secret
should have <code>no_log: true</code>, and nothing should ever <code>debug</code> one.</p>
<h3 id="4-its-only-the-lab-password">4. &ldquo;It&rsquo;s only the lab password&rdquo;</h3>
<p>Lab passwords get reused, lab repos get made public, and lab inventories get copied into production. Build the
habit where it&rsquo;s cheap.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/ansible-101/#chapter-7">Chapter 7 of the lab</a> moves the switch password into a vault file with the
<code>vault_</code> pattern, keeps the key out of Git, and encrypts the SNMP community inline with <code>encrypt_string</code>.</p>
<p>Next, in <a href="/lessons/ansible-101/production/">lesson 8</a>, the finale: running all of this the way production does, in
an execution environment, lint-clean, from a pipeline.</p>
]]></content:encoded></item><item><title>Ansible Roles and Collections for Network Automation (Ansible 101 for Networking, Lesson 6)</title><link>https://networkdoodles.com/lessons/ansible-101/roles/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/roles/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>capeos</category><category>howto</category><description>Turn network playbooks into Ansible roles: tasks, defaults and handlers, the precedence rule behind role defaults, prefixed role variables, and collections.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Five lessons in, the lab has a playbook for banners, one for base config, one for interfaces, one for facts and
one for a report. Each works. Together they&rsquo;re the start of a problem every team hits: which playbook do I run,
in what order, and why is the save handler defined twice?</p>
<p><strong>Roles</strong> are Ansible&rsquo;s answer. A role packages tasks, their defaults, their handlers and their templates into
one folder you can run, reuse and share. This lesson turns the lab&rsquo;s playbooks into two roles and one
<code>site.yml</code>, and explains the one precedence rule that makes roles click.</p>
<hr>
<h2 id="what-a-role-is">What a role is</h2>
<p>A role is a folder with a fixed layout. Ansible knows where to look for each piece:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">roles/base/
</span></span><span class="line"><span class="cl">├── tasks/main.yml       ← what the role does (required)
</span></span><span class="line"><span class="cl">├── defaults/main.yml    ← its variables, at the lowest precedence there is
</span></span><span class="line"><span class="cl">├── handlers/main.yml    ← its handlers (the save from lesson 5)
</span></span><span class="line"><span class="cl">├── templates/           ← its Jinja2 templates, found by name
</span></span><span class="line"><span class="cl">└── meta/main.yml        ← who wrote it, what it needs
</span></span></code></pre></div><p>You don&rsquo;t create that by hand: <code>ansible-galaxy role init</code> scaffolds it, with a stub <code>main.yml</code> in every
folder. Delete the ones you don&rsquo;t use; an empty <code>vars/</code> folder is noise.</p>
<p>The lab ends up with two roles:</p>
<ul>
<li><strong><code>base</code></strong>: banners, contact, domain, location, LLDP, NTP, and the save handler.</li>
<li><strong><code>interfaces</code></strong>: the two port loops from lesson 4.</li>
</ul>
<p>And one playbook that runs them:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># playbooks/site.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">hosts</span><span class="p">:</span><span class="w"> </span><span class="l">fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">gather_facts</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">roles</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">base</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="l">interfaces</span><span class="w">
</span></span></span></code></pre></div><p>That&rsquo;s the whole fabric in seven lines. The playbook no longer says <em>what</em> it does, only <em>which roles</em> apply
to <em>which hosts</em>. As the network grows, <code>site.yml</code> becomes the map: spines get these roles, leaves get these,
the border gets these.</p>
<hr>
<h2 id="moving-tasks-into-a-role">Moving tasks into a role</h2>
<p>The tasks move over almost unchanged. Here&rsquo;s the start of the role&rsquo;s <code>tasks/main.yml</code>, with the banner and
config-line tasks from lessons 2 and 3:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># roles/base/tasks/main.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Login banner</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">cisco.ios.ios_banner</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">banner</span><span class="p">:</span><span class="w"> </span><span class="l">login</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">text</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ base_banner_text }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">state</span><span class="p">:</span><span class="w"> </span><span class="l">present</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">notify</span><span class="p">:</span><span class="w"> </span><span class="l">Save the running config</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Message of the day</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">cisco.ios.ios_banner</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">banner</span><span class="p">:</span><span class="w"> </span><span class="l">motd</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">text</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ base_motd_text }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">state</span><span class="p">:</span><span class="w"> </span><span class="l">present</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">notify</span><span class="p">:</span><span class="w"> </span><span class="l">Save the running config</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Contact, domain, location and LLDP</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">cisco.ios.ios_config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">lines</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span>- <span class="s2">&#34;snmp-server contact {{ base_contact }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span>- <span class="s2">&#34;ip domain name {{ base_domain_name }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span>- <span class="s2">&#34;snmp-server location {{ location }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span>- <span class="l">lldp run</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">notify</span><span class="p">:</span><span class="w"> </span><span class="l">Save the running config</span><span class="w">
</span></span></span></code></pre></div><p>The NTP task follows, as it was in lesson 3, and every task notifies the save handler, which now lives in
<code>handlers/main.yml</code>.</p>
<p>Three things changed:</p>
<ol>
<li><strong>No play wrapper.</strong> A role&rsquo;s tasks file is just a list of tasks. The play lives in <code>site.yml</code>.</li>
<li><strong>The hard-coded strings became variables</strong>, and those variables got defaults.</li>
<li><strong>Four single-line tasks became one.</strong> <code>lines:</code> is a list, and <code>ios_config</code> checks each line on its own, so
the contact, domain, location and LLDP lines can share a task.</li>
</ol>
<hr>
<h2 id="defaults-the-values-nobody-had-to-set">Defaults: the values nobody had to set</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># roles/base/defaults/main.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">base_banner_text</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;Managed by Ansible - Network Doodles lab&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">base_motd_text</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;Authorized access only. Changes go through Git.&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">base_contact</span><span class="p">:</span><span class="w"> </span><span class="l">netops@networkdoodles.com</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">base_domain_name</span><span class="p">:</span><span class="w"> </span><span class="l">lab.networkdoodles.com</span><span class="w">
</span></span></span></code></pre></div><p>Role defaults are the <strong>lowest-precedence variables in Ansible</strong>. Everything beats them: <code>group_vars</code>,
<code>host_vars</code>, play vars, <code>-e</code>. That sounds like a weakness. It&rsquo;s the point.</p>
<p>A role with good defaults works out of the box, and anyone using it can override exactly the values they care
about without touching the role. The leaves want a different message of the day? One line, in the place you&rsquo;d
expect:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># inventory/group_vars/leaves.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">base_motd_text</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;Leaf switch. Hosts plug in here; uplinks go to spine1.&#34;</span><span class="w">
</span></span></span></code></pre></div><p>Run <code>site.yml</code> and the leaves show the new message while spine1 keeps the role&rsquo;s default. Nobody edited the
role. That&rsquo;s the precedence chain from lesson 3 doing its job: <strong>host beats group, specific group beats general
group, and everything beats role defaults.</strong></p>
<p>There&rsquo;s also a <code>vars/main.yml</code> in a role, and it&rsquo;s the opposite: high precedence, hard to override. Use it
for values the role needs fixed (a path, an API version), and almost never for anything a user might
reasonably want to change.</p>

<figure class="netsim" data-netsim tabindex="0" aria-label="site.yml applies the base role to the fabric: its default message of the day reaches all three switches, group_vars/leaves.yml overrides it for the leaves, host_vars/leaf2.yml overrides that for leaf2, and a role&#39;s vars/ would beat them all. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="site.yml applies the base role to the fabric: its default message of the day reaches all three switches, group_vars/leaves.yml overrides it for the leaves, host_vars/leaf2.yml overrides that for leaf2, and a role&#39;s vars/ would beat them all"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":360,"links":[],"narrow":{"at":{"def":[180,140,330],"gv":[180,205,330],"hv":[180,270,330],"leaf1":[180,450],"leaf2":[300,450],"role":[235,50,220],"site":[60,50],"spine1":[60,450],"vars":[180,335,330]},"h":540,"w":360},"nodes":{"def":{"h":44,"kind":"box","label":"defaults/main.yml","sub":"lowest precedence","w":230,"x":320,"y":115},"gv":{"c":"amber","h":44,"hidden":true,"kind":"box","label":"group_vars/leaves.yml","sub":"the leaves","w":230,"x":320,"y":185},"hv":{"c":"amber","h":44,"hidden":true,"kind":"box","label":"host_vars/leaf2.yml","sub":"leaf2 only","w":230,"x":320,"y":255},"leaf1":{"kind":"switch","label":"leaf1","sub":"leaves","x":640,"y":170},"leaf2":{"kind":"switch","label":"leaf2","sub":"leaves","x":640,"y":275},"role":{"h":44,"kind":"box","label":"roles/base","sub":"tasks · handlers","w":230,"x":320,"y":45},"site":{"kind":"file","label":"site.yml","sub":"hosts: fabric","x":80,"y":60},"spine1":{"kind":"switch","label":"spine1","sub":"spines","x":640,"y":65},"vars":{"h":44,"hidden":true,"kind":"box","label":"roles/base/vars/main.yml","sub":"high precedence","w":230,"x":320,"y":325}},"steps":[{"code":{"hl":[4],"lines":["- name: Fabric","  hosts: fabric","  gather_facts: false","  roles:","    - base","    - interfaces"],"title":"playbooks/site.yml"},"hot":["site","role","def"],"packets":[{"label":"base","path":["site","role"]}],"text":"The playbook only says which roles apply to which hosts. The role brings its tasks, handlers and defaults.","title":"site.yml applies the role."},{"code":null,"hot":["def"],"packets":[{"label":"default","path":["def","spine1"]},{"label":"default","path":["def","leaf1"]},{"label":"default","path":["def","leaf2"]}],"table":{"cols":["host","value","from"],"rows":[["spine1","Authorized access only. Changes go through Git.","defaults/main.yml"],["leaf1","Authorized access only. Changes go through Git.","defaults/main.yml"],["leaf2","Authorized access only. Changes go through Git.","defaults/main.yml"]],"title":"base_motd_text"},"text":"Every switch gets the role's `base_motd_text`. Role defaults lose to everything, which is the point.","title":"Defaults: what a switch gets when nobody says otherwise."},{"hot":["gv"],"packets":[{"c":"amber","label":"leaves","path":["gv","leaf1"]},{"c":"amber","label":"leaves","path":["gv","leaf2"]}],"show":["gv"],"table":{"cols":["host","value","from"],"hl":[1,2],"rows":[["spine1","Authorized access only. Changes go through Git.","defaults/main.yml"],["leaf1","Leaf switch. Hosts plug in here; uplinks go to spine1.","group_vars/leaves.yml"],["leaf2","Leaf switch. Hosts plug in here; uplinks go to spine1.","group_vars/leaves.yml"]],"title":"base_motd_text"},"text":"One line in `group_vars/leaves.yml`. spine1 keeps the default, and nobody edited the role.","title":"The leaves override one value."},{"hot":["hv"],"packets":[{"c":"amber","label":"leaf2","path":["hv","leaf2"]}],"show":["hv"],"table":{"cols":["host","value","from"],"hl":2,"rows":[["spine1","Authorized access only. Changes go through Git.","defaults/main.yml"],["leaf1","Leaf switch. Hosts plug in here; uplinks go to spine1.","group_vars/leaves.yml"],["leaf2","leaf2: the lab's test leaf. Expect changes.","host_vars/leaf2.yml"]],"title":"base_motd_text"},"text":"Host beats group, and everything beats role defaults. leaf2 gets its own message.","title":"One host overrides the group."},{"good":["spine1","leaf1","leaf2"],"hot":["role"],"packets":[{"c":"green","label":"banner motd","path":["role","spine1"]},{"c":"green","label":"banner motd","path":["role","leaf1"]},{"c":"green","label":"banner motd","path":["role","leaf2"]}],"set":{"leaf1":"leaves MOTD","leaf2":"its own MOTD","spine1":"default MOTD"},"text":"The role's `Message of the day` task sends `{{ base_motd_text }}`, and each switch gets the value that won.","title":"One task, three messages."},{"dim":["gv","hv"],"hot":["vars"],"say":{"vars":"hard to override"},"sayAt":{"vars":{"narrow":"below","wide":"right"}},"show":["vars"],"text":"A role's `vars/main.yml` beats group_vars and host_vars. Keep it for what the role needs fixed, never for what a user might change.","title":"vars/ is the opposite."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<h3 id="why-the-base_-prefix">Why the <code>base_</code> prefix</h3>
<p>My first version of the role had <code>banner_text</code> and <code>contact</code>. It worked. Then ansible-lint (lesson 8) flagged
every one of them, and it was right. Variables are global in Ansible: if two roles both define <code>contact</code>, they
silently share it, and whichever wins precedence wins for both. Prefixing every role variable with the role&rsquo;s
name (<code>base_contact</code>) makes collisions impossible and tells the reader exactly where a value comes from.</p>
<p>Inventory-level facts that describe the switch itself, like <code>location</code> or <code>interfaces</code>, stay unprefixed.
They&rsquo;re not the role&rsquo;s; they belong to the host, and any role can read them.</p>
<hr>
<h2 id="collections-roles-bigger-sibling">Collections: roles&rsquo; bigger sibling</h2>
<p>You&rsquo;ve been using a collection since lesson 1: <code>cisco.ios</code>. A <strong>collection</strong> is the distribution format for
Ansible content. It can hold modules, plugins, roles and playbooks, and it&rsquo;s versioned and installed as a unit.
The lab&rsquo;s <code>requirements.yml</code> pins exactly which ones it uses:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nt">collections</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">cisco.ios</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">version</span><span class="p">:</span><span class="w"> </span><span class="m">11.6.0</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">ansible.netcommon</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">version</span><span class="p">:</span><span class="w"> </span><span class="m">8.7.1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">ansible.utils</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">version</span><span class="p">:</span><span class="w"> </span><span class="m">6.1.1</span><span class="w">
</span></span></span></code></pre></div><p><code>ansible-galaxy collection install -r requirements.yml</code> installs exactly those versions, on your laptop, in CI,
or into an execution environment (lesson 8).</p>
<p>How I think about the three levels:</p>
<table>
  <thead>
      <tr>
          <th></th>
          <th>Holds</th>
          <th>Use it for</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>Playbook</strong></td>
          <td>Plays: which hosts get which roles</td>
          <td>Your site, your inventory</td>
      </tr>
      <tr>
          <td><strong>Role</strong></td>
          <td>Tasks, defaults, handlers, templates</td>
          <td>One job, done well, reusable</td>
      </tr>
      <tr>
          <td><strong>Collection</strong></td>
          <td>Modules, plugins, and roles</td>
          <td>Sharing across teams or publishing</td>
      </tr>
  </tbody>
</table>
<p>Start with roles inside your repo, like the lab does. Package them into a collection when a second team wants
them. And <strong>always pin versions</strong> in <code>requirements.yml</code>: a collection upgrade that changes a module&rsquo;s behavior
should be a reviewed change in Git, not a surprise on a Tuesday.</p>
<hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-one-role-per-playbook">1. One role per playbook</h3>
<p>A role called <code>site</code> that contains everything isn&rsquo;t a role, it&rsquo;s a renamed playbook. Split by job: base
config, interfaces, routing, security. Each role should be explainable in one sentence.</p>
<h3 id="2-configuration-in-varsmainyml">2. Configuration in <code>vars/main.yml</code></h3>
<p>Putting user-facing values in <code>vars/</code> means nobody can override them without editing the role. If you find
yourself copying a role to change one value, that value belonged in <code>defaults/</code>.</p>
<h3 id="3-roles-that-reach-into-other-roles">3. Roles that reach into other roles</h3>
<p>A role that reads another role&rsquo;s variables, or notifies another role&rsquo;s handler, is two roles pretending to be
independent. Pass what you need through variables, or declare a dependency in <code>meta/main.yml</code>.</p>
<h3 id="4-unpinned-collections">4. Unpinned collections</h3>
<p><code>ansible-galaxy collection install cisco.ios</code> installs whatever is newest today. Your pipeline will install
something different next month. Pin everything.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/ansible-101/#chapter-6">Chapter 6 of the lab</a> turns the playbooks into the <code>base</code> and <code>interfaces</code>
roles run from <code>site.yml</code>, then gives the leaves, and leaf2 alone, their own message of the day without
touching the role.</p>
<p>Next, in <a href="/lessons/ansible-101/secrets/">lesson 7</a>, we finally deal with the password that&rsquo;s been sitting in plain
text since lesson 1.</p>
]]></content:encoded></item><item><title>Ansible Handlers, Tags and block/rescue on Network Devices (Ansible 101 for Networking, Lesson 5)</title><link>https://networkdoodles.com/lessons/ansible-101/handlers-tags-errors/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/handlers-tags-errors/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>capeos</category><category>howto</category><description>Save switch config only when something changed with handlers, run part of a playbook with tags, and recover from a failed change with block, rescue and always.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>By the end of <a href="/lessons/ansible-101/loops-and-templates/">lesson 4</a> the playbooks configure every port on every
switch from data. They&rsquo;re also missing three things every network engineer cares about the moment the
automation touches production:</p>
<ul>
<li>The config isn&rsquo;t <strong>saved</strong>. Reboot a switch and the changes are gone.</li>
<li>You can&rsquo;t run <strong>part</strong> of a playbook. Fixing one port description means re-running everything.</li>
<li>Nothing handles a change that <strong>fails halfway</strong>, which is the one that actually ruins your night.</li>
</ul>
<p>This lesson fixes all three.</p>
<hr>
<h2 id="handlers-do-it-once-only-if-something-changed">Handlers: do it once, only if something changed</h2>
<p>On these switches, as on most classic CLIs, your playbooks change the <strong>running-config</strong>. Reboot and the switch
loads the <strong>startup-config</strong>, so anything nobody saved with <code>write memory</code> is gone. Saving the config after
every task is wasteful, and saving it when nothing changed is worse: it rewrites the startup config for no
reason, and on some platforms it&rsquo;s slow. What you want is &ldquo;if anything changed, save
once, at the end&rdquo;. That&rsquo;s a <strong>handler</strong>.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl">- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Base config</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">hosts</span><span class="p">:</span><span class="w"> </span><span class="l">fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">gather_facts</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">tasks</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">NTP servers, from group_vars</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_ntp_global</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">servers</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ ntp_servers }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">notify</span><span class="p">:</span><span class="w"> </span><span class="l">Save the running config</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Where the switch lives, from host_vars</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">lines</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="s2">&#34;snmp-server location {{ location }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">notify</span><span class="p">:</span><span class="w"> </span><span class="l">Save the running config</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">handlers</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Save the running config</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_command</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">commands</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="l">write memory</span><span class="w">
</span></span></span></code></pre></div><p>A handler is a task that only runs when another task <strong>notifies</strong> it, and only if that task reported
<code>changed</code>. Both tasks above notify the same handler, but it runs <strong>once</strong>, after all the tasks have finished,
as a <code>RUNNING HANDLER [Save the running config]</code> section at the end of the output. If only leaf1&rsquo;s NTP had
drifted, only leaf1 would change, and only leaf1 would save.</p>
<p>Run it again: both tasks report <code>ok</code>, nothing notifies, and the handler doesn&rsquo;t run at all. That&rsquo;s exactly
right. Two details are worth a second look:</p>
<ul>
<li>The handler reports <strong><code>ok</code></strong>, not <code>changed</code>. <code>ios_command</code> can&rsquo;t know whether <code>write memory</code> changed
anything; it only knows the command ran. (Remember lesson 2: <code>changed</code> is only as honest as the module.)</li>
<li>The handler is matched <strong>by name</strong>. Typo the name in <code>notify</code> and Ansible stops with an error saying the
requested handler wasn&rsquo;t found, which is the behavior you want.</li>
</ul>

<figure class="netsim" data-netsim tabindex="0" aria-label="Two tasks on leaf1 both report changed and notify the save handler, which is queued once and runs once after the last task; a second run notifies nothing; then a block whose second step fails on the leaves, and the rescue that puts the MTU back. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="Two tasks on leaf1 both report changed and notify the save handler, which is queued once and runs once after the last task; a second run notifies nothing; then a block whose second step fails on the leaves, and the rescue that puts the MTU back"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":340,"links":[],"narrow":{"at":{"b1":[180,45,340],"b2":[180,105,340],"h":[180,185,340],"leaf1":[180,320],"leaf2":[300,320],"rs":[180,185,340],"spine1":[60,320],"t1":[180,45,340],"t2":[180,105,340]},"h":420,"w":360},"nodes":{"b1":{"h":44,"hidden":true,"kind":"box","label":"Step 1 · lower the uplink MTU","sub":"mtu: 1500","w":330,"x":200,"y":60},"b2":{"h":44,"hidden":true,"kind":"box","label":"Step 2 · an MTU no switch supports","sub":"mtu: 99999","w":330,"x":200,"y":150},"h":{"h":44,"kind":"box","label":"Save the running config","sub":"handler: write memory","w":330,"x":200,"y":270},"leaf1":{"kind":"switch","label":"leaf1","sub":"leaves","x":620,"y":165},"leaf2":{"kind":"switch","label":"leaf2","sub":"leaves","x":620,"y":270},"rs":{"h":44,"hidden":true,"kind":"box","label":"rescue: roll back","sub":"mtu: 9100","w":330,"x":200,"y":270},"spine1":{"kind":"switch","label":"spine1","sub":"spines","x":620,"y":60},"t1":{"h":44,"kind":"box","label":"NTP servers, from group_vars","sub":"notify: Save the running config","w":330,"x":200,"y":60},"t2":{"h":44,"kind":"box","label":"Where the switch lives, from host_vars","sub":"notify: Save the running config","w":330,"x":200,"y":150}},"steps":[{"code":{"hl":[1,3],"lines":["    - name: NTP servers, from group_vars","      notify: Save the running config","    - name: Where the switch lives, from host_vars","      notify: Save the running config","  handlers:","    - name: Save the running config","      cisco.ios.ios_command:","        commands:","          - write memory"],"title":"playbooks/base.yml"},"hot":["t1","t2","h"],"table":{"cols":["host","notified by","handler runs"],"empty":"empty","rows":[],"title":"handler queue"},"text":"Both tasks notify `Save the running config`. A handler runs only if a task that notifies it reports `changed`.","title":"Two tasks, one handler."},{"good":["spine1","leaf2"],"hot":["t1","leaf1"],"packets":[{"c":"amber","label":"changed","path":["t1","leaf1"]},{"at":1,"c":"amber","label":"notify","path":["leaf1","h"]}],"table":{"cols":["host","notified by","handler runs"],"rows":[["leaf1","NTP servers","queued"]],"title":"handler queue"},"text":"The NTP task changes leaf1 and notifies the handler. spine1 and leaf2 already match: `ok`, no notify.","title":"leaf1's NTP has drifted."},{"hot":["t2","leaf1"],"packets":[{"c":"amber","label":"changed","path":["t2","leaf1"]},{"at":1,"c":"amber","label":"notify","path":["leaf1","h"]}],"table":{"cols":["host","notified by","handler runs"],"rows":[["leaf1","NTP servers, location","queued once"]],"title":"handler queue"},"text":"Say leaf1's location changes too. That task notifies the same handler, and the queue still holds it once.","title":"A second notify, still one entry."},{"good":["leaf1"],"hot":["h"],"packets":[{"c":"green","label":"write memory","path":["h","leaf1"]}],"table":{"cols":["host","notified by","handler runs"],"rows":[["leaf1","NTP servers, location","once, at the end"]],"title":"handler queue"},"text":"`RUNNING HANDLER [Save the running config]`: one `write memory`, on leaf1 only. It reports `ok`: `ios_command` can't know.","title":"After the last task, it runs once."},{"dim":["h"],"good":["spine1","leaf1","leaf2"],"table":{"cols":["host","notified by","handler runs"],"empty":"nothing notified","rows":[],"title":"handler queue"},"text":"Both tasks report `ok` on every switch, so the handler never runs. To see a handler fire, you need a change.","title":"Run it again: nothing notifies."},{"bad":["leaf1","leaf2"],"code":null,"dim":["spine1"],"hide":["t1","t2","h"],"packets":[{"c":"amber","label":"mtu 1500","path":["b1","leaf1"]},{"c":"amber","label":"mtu 1500","path":["b1","leaf2"]},{"at":1,"c":"red","end":"drop","label":"mtu 99999","path":["b2","leaf1"]},{"at":1,"c":"red","end":"drop","label":"mtu 99999","path":["b2","leaf2"]}],"say":{"leaf1":"% Invalid input\ndetected"},"sayAt":{"leaf1":{"narrow":"above","wide":"left"}},"set":{"leaf1":"Gi1 MTU 1500","leaf2":"Gi1 MTU 1500"},"show":["b1","b2"],"table":{"cols":["step","result"],"rows":[["Step 1 · mtu 1500","applied"],["Step 2 · mtu 99999","failed"]],"title":"leaves, GigabitEthernet1"},"text":"On the leaves, step 1 lowers the uplink MTU to 1500. Step 2 is rejected. Without a rescue, the uplink stays at 1500.","title":"A change that fails halfway."},{"dim":["spine1","b1","b2"],"good":["leaf1","leaf2"],"hot":["rs"],"packets":[{"c":"green","label":"mtu 9100","path":["rs","leaf1"]},{"c":"green","label":"mtu 9100","path":["rs","leaf2"]}],"set":{"leaf1":"Gi1 MTU 9100","leaf2":"Gi1 MTU 9100"},"show":["rs"],"table":{"cols":["host","failed","rescued"],"rows":[["leaf1","0","1"],["leaf2","0","1"]],"title":"PLAY RECAP"},"text":"The rescue re-applies 9100. `always` reads the port's config back either way. The recap says `failed=0`, `rescued=1`.","title":"rescue puts it back, always reads it back."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<p>Here&rsquo;s a trap I walked into building the lab: if your switches <em>already</em> have the config, adding a handler
and running the playbook does nothing at all, because nothing changes, so nothing notifies. That&rsquo;s correct
behavior, and it confuses everyone the first time. To see a handler fire, you need a change for it to react
to.</p>
<p>(Some modules offer a shortcut: <code>cisco.ios.ios_config</code> has <code>save_when: changed</code>. It&rsquo;s handy. Handlers are the
general tool; they work for any module, on any platform, and for things other than saving.)</p>
<hr>
<h2 id="tags-run-part-of-a-playbook">Tags: run part of a playbook</h2>
<p>Tag your tasks, and you can run just the ones you need:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Description and no shutdown, one port at a time</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="l">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">tags</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="l">descriptions]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Jumbo MTU on uplinks only</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="l">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">tags</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="l">mtu]</span><span class="w">
</span></span></span></code></pre></div><p><code>--tags descriptions</code> on the command line runs only the tasks tagged <code>descriptions</code>; <code>--skip-tags mtu</code> runs
everything except the MTU task. Add <code>--list-tasks</code> and Ansible prints the tasks a run <em>would</em> include and
touches nothing, which is how you check what a tag selects before you trust it:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">playbook: playbooks/interfaces.yml
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  play #1 (fabric): Interfaces	TAGS: []
</span></span><span class="line"><span class="cl">    tasks:
</span></span><span class="line"><span class="cl">      Description and no shutdown, one port at a time	TAGS: [descriptions]
</span></span></code></pre></div><p>Tags are great for speed and for scoping a change (&ldquo;only the NTP part tonight&rdquo;). They&rsquo;re also easy to abuse.
Tag by <strong>what the task configures</strong> (<code>ntp</code>, <code>descriptions</code>, <code>mtu</code>), not by when you run it (<code>tuesday</code>,
<code>quick</code>). And remember that a tag filter can skip a task another task depends on; <code>--list-tasks</code> is how you
catch that before it catches you.</p>
<hr>
<h2 id="when-a-change-fails-halfway">When a change fails halfway</h2>
<p>This is the one that matters. A change with two steps, where the second one fails, leaves the device in a state
nobody designed: not the old config, not the new one. Ansible&rsquo;s answer is <strong><code>block</code></strong>, <strong><code>rescue</code></strong> and
<strong><code>always</code></strong>, which work like try, except and finally:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Change the uplinks, then roll back if anything fails</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">block</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Step 1 · lower the uplink MTU (this works)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">cisco.ios.ios_interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">GigabitEthernet1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">mtu</span><span class="p">:</span><span class="w"> </span><span class="m">1500</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Step 2 · an MTU no switch supports (this fails)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">cisco.ios.ios_interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">GigabitEthernet1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">mtu</span><span class="p">:</span><span class="w"> </span><span class="m">99999</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">rescue</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Roll back to the known-good MTU</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">cisco.ios.ios_interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">GigabitEthernet1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="nt">mtu</span><span class="p">:</span><span class="w"> </span><span class="m">9100</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">always</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Read the port&#39;s config back</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">cisco.ios.ios_command</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">commands</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">              </span>- <span class="l">show running-config interface GigabitEthernet1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">register</span><span class="p">:</span><span class="w"> </span><span class="l">uplink_config</span><span class="w">
</span></span></span></code></pre></div><p>Step 1 works: the uplink&rsquo;s MTU drops to 1500. Step 2 fails, because the switch rejects the value with
<code>% Invalid input detected</code>, exactly as it would if you typed it. Without a rescue, that&rsquo;s where Ansible stops
for that host, and the uplink stays at 1500: not the old config, not the new one.</p>
<p>With the rescue, Ansible runs the <strong>rescue</strong> tasks for that host instead, which put the MTU back to 9100. The
<strong>always</strong> tasks run either way and read the port&rsquo;s config back from the switch, so every run ends with proof
of the state it left behind. (<code>register</code> keeps the show command&rsquo;s output, as promised in lesson 3.) Inside a
rescue, <code>ansible_failed_task</code> is the task that failed, which makes for an honest log message.</p>
<p>The recap tells the story: <code>failed=0</code>, <code>rescued=1</code>. Something went wrong, and it was handled. That distinction
matters in a pipeline: a rescued play is a success with a story, not a red build.</p>
<p>A classic CLI applies each line the moment it&rsquo;s accepted. The switch refused step 2&rsquo;s line, so nothing from
step 2 took, but step 1 was already live. That&rsquo;s why the rescue matters.</p>
<h3 id="rollback-is-a-design-decision-not-a-keyword">Rollback is a design decision, not a keyword</h3>
<p><code>rescue</code> doesn&rsquo;t magically undo anything. It runs whatever you wrote. In the lab, the rescue re-applies a
known-good value, which is simple and honest. Real options, from simplest to strongest:</p>
<ol>
<li><strong>Re-apply the known-good values</strong> (this post). Easy; you have to know what &ldquo;good&rdquo; was.</li>
<li><strong>Re-run the whole playbook from Git</strong>. If your playbooks describe the full intended state, the last
good commit <em>is</em> your rollback.</li>
<li><strong>Let the device do it.</strong> Platforms with a candidate config often support a confirmed commit: apply the
change, and if it isn&rsquo;t confirmed within N seconds, the device reverts on its own. A CLI that applies
lines as you type them, like the lab&rsquo;s, has no commit to confirm, so this one depends on your platform.
Where it exists, it&rsquo;s the one that saves you when the change cuts off your own management access.</li>
</ol>
<hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-ignore_errors-true-as-a-lifestyle">1. <code>ignore_errors: true</code> as a lifestyle</h3>
<p>It turns every failure into a shrug, and the play carries on as if the change worked. If a failure is
expected and safe, handle it with <code>rescue</code> or <code>failed_when</code> and say why in the task name. If it isn&rsquo;t, let it
fail.</p>
<h3 id="2-saving-config-in-every-task">2. Saving config in every task</h3>
<p>A save after every change is slow, noisy in the recap, and leaves you no way to tell &ldquo;saved because something
changed&rdquo; from &ldquo;saved because it always does&rdquo;. Notify a handler.</p>
<h3 id="3-handlers-that-never-run">3. Handlers that never run</h3>
<p>A play that fails before the end doesn&rsquo;t run its handlers by default, so a change that applied before the
failure is never saved. If that matters, use <code>force_handlers: true</code> on the play, or <code>meta: flush_handlers</code> at
the point where you want pending handlers to run.</p>
<h3 id="4-tags-as-a-substitute-for-structure">4. Tags as a substitute for structure</h3>
<p>If every run uses <code>--tags</code>, the playbook is really three playbooks. Split it. That&rsquo;s lesson 6.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/ansible-101/#chapter-5">Chapter 5 of the lab</a> adds the save handler to the base playbook, tags the
interface tasks, and has you finish the rescue and always sections so a failed change leaves the uplinks the
way it found them.</p>
<p>Next, in <a href="/lessons/ansible-101/roles/">lesson 6</a>, the playbooks become roles: reusable units with their own
defaults, handlers and tasks, and the precedence rule that makes role defaults so useful.</p>
]]></content:encoded></item><item><title>Ansible Loops, when and Jinja2 Templates for Network Config (Ansible 101 for Networking, Lesson 4)</title><link>https://networkdoodles.com/lessons/ansible-101/loops-and-templates/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/loops-and-templates/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>jinja2</category><category>capeos</category><category>howto</category><description>Configure every port on every switch from a data list with loop, treat uplinks differently with when, and render a fabric report with Jinja2 templates.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>So far every task in this course has set one thing: one banner, one list of NTP servers, one location. Real network
config isn&rsquo;t like that. A switch has forty-eight ports, and you want every one of them described, enabled and
sized correctly, from data, without forty-eight tasks.</p>
<p>This lesson covers the three tools that make that possible: <strong>loops</strong> to repeat a task over a list,
<strong>conditionals</strong> to skip the items that don&rsquo;t apply, and <strong>templates</strong> to turn data into any text you like.</p>
<hr>
<h2 id="ports-as-data">Ports as data</h2>
<p>Start with the data. Each switch&rsquo;s ports go in its host file, next to the location from
<a href="/lessons/ansible-101/variables-and-facts/">lesson 3</a>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># inventory/host_vars/leaf1.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">location</span><span class="p">:</span><span class="w"> </span><span class="l">Row A, rack 2</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- {<span class="w"> </span><span class="nt">name: GigabitEthernet1, description</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;to spine1 Gi1&#34;</span><span class="nt">, uplink</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span>}<span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- {<span class="w"> </span><span class="nt">name: GigabitEthernet2, description</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;host1&#34;</span><span class="w"> </span>}<span class="w">
</span></span></span></code></pre></div><p>Each port is a small dictionary: a name, a description, and, for uplinks, <code>uplink: true</code>. The <code>{ }</code> form is
just compact YAML for a dictionary on one line; it reads better than three lines per port when you have
dozens.</p>
<p>This list is now the definition of leaf1&rsquo;s ports. Want to add a port? Add a line. Want to know what a port is
for? Read the file. The playbook doesn&rsquo;t change.</p>
<hr>
<h2 id="loop-one-task-every-port">loop: one task, every port</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Description and no shutdown, one port at a time</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ item.name }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">description</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ item.description }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">enabled</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">loop</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ interfaces }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">loop_control</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">label</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ item.name }}&#34;</span><span class="w">
</span></span></span></code></pre></div><p><code>loop</code> runs the task once per entry in the list, and each time <strong><code>item</code></strong> is the current entry. So
<code>{{ item.name }}</code> is <code>GigabitEthernet1</code> the first time round and <code>GigabitEthernet2</code> the second.</p>
<p><code>loop_control: label</code> controls what Ansible prints for each item. Without it, Ansible prints the entire
dictionary for every iteration, which gets unreadable fast. With it, each port gets one short line, like
<code>changed: [leaf1] =&gt; (item=GigabitEthernet1)</code>.</p>
<p>Each switch loops over <em>its own</em> <code>interfaces</code>, because the variable comes from <code>host_vars</code>. One task, three
switches, six ports, zero hostnames in the playbook.</p>
<h3 id="why-a-resource-module-for-ports">Why a resource module for ports</h3>
<p>The task uses <code>cisco.ios.ios_interfaces</code>, not the <code>ios_config</code> lines from lesson 2, and <code>enabled: true</code> is the
reason. A port that&rsquo;s up shows <strong>no</strong> <code>no shutdown</code> line in the running config: &ldquo;not shut down&rdquo; is the
default, and defaults don&rsquo;t print. So <code>ios_config</code> with <code>no shutdown</code> in its lines would never find that line,
and would send it on every run. <code>ios_interfaces</code> is a resource module: it reads each interface&rsquo;s config into
data (description, enabled, MTU), compares that with what you asked for, and knows that <code>enabled: true</code> means
&ldquo;there should be no <code>shutdown</code> line&rdquo;. You describe the port; it works out the commands.</p>
<p>A note on performance: a loop makes one change per item, which means a round trip to the switch per port.
For a lab, or a handful of ports, that&rsquo;s perfect, because you can see exactly which port changed. For 48 ports
on 200 switches, you&rsquo;d hand <code>ios_interfaces</code> the whole list in one <code>config:</code> instead. Get it right first; make
it fast when it matters.</p>
<hr>
<h2 id="when-not-every-item-applies">when: not every item applies</h2>
<p>Uplinks get a jumbo MTU; host ports don&rsquo;t. That&rsquo;s a <strong>conditional</strong>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Jumbo MTU on uplinks only</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_interfaces</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ item.name }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">mtu</span><span class="p">:</span><span class="w"> </span><span class="m">9100</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">loop</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ interfaces }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">loop_control</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">label</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ item.name }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">when</span><span class="p">:</span><span class="w"> </span><span class="l">item.uplink | default(false)</span><span class="w">
</span></span></span></code></pre></div><p><code>when</code> is evaluated for each item. If it&rsquo;s true, the task runs for that item; if not, Ansible skips it and says
so. On leaf1, <code>GigabitEthernet1</code> (the uplink) gets the MTU and <code>GigabitEthernet2</code> (host1&rsquo;s port) shows
<code>skipping</code>. On spine1 both ports are uplinks, so nothing is skipped.</p>
<p>Two details worth copying:</p>
<ul>
<li><strong>No <code>{{ }}</code> in <code>when</code>.</strong> It&rsquo;s already an expression. Writing <code>when: &quot;{{ item.uplink }}&quot;</code> works but earns a
warning, and it&rsquo;s a sign someone copied from an old blog post.</li>
<li><strong><code>| default(false)</code></strong> handles the ports that don&rsquo;t have an <code>uplink</code> key at all. Without it, the first host
port fails with &ldquo;&lsquo;dict object&rsquo; has no attribute &lsquo;uplink&rsquo;&rdquo;. Defaults on optional keys are what keep your data
files short.</li>
</ul>
<p><code>when</code> works on whole tasks too, not just loop items. <code>when: inventory_hostname in groups['spines']</code> runs a
task on the spines only; that&rsquo;s often cleaner than writing a separate play.</p>

<figure class="netsim" data-netsim tabindex="0" aria-label="leaf1&#39;s two ports as a list in host_vars: one loop task configures each port in turn, a when condition gives the jumbo MTU to the uplink and skips the host port, and a template turns the same data into the fabric report. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="leaf1&#39;s two ports as a list in host_vars: one loop task configures each port in turn, a when condition gives the jumbo MTU to the uplink and skips the host port, and a template turns the same data into the fabric report"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":340,"links":[],"narrow":{"at":{"data":[80,60],"gi1":[180,190,300],"gi2":[180,270,300],"leaf1":[270,60],"rep":[180,370]},"h":450,"w":360},"nodes":{"data":{"kind":"file","label":"leaf1.yml","sub":"host_vars/","x":90,"y":160},"gi1":{"h":44,"kind":"box","label":"GigabitEthernet1","sub":"to spine1 Gi1 · uplink","w":230,"x":340,"y":100},"gi2":{"h":44,"kind":"box","label":"GigabitEthernet2","sub":"host1","w":230,"x":340,"y":220},"leaf1":{"kind":"switch","label":"leaf1","sub":"Row A, rack 2","x":640,"y":110},"rep":{"hidden":true,"kind":"file","label":"fabric-report.md","sub":"build/","x":640,"y":260}},"steps":[{"code":{"lines":["interfaces:","  - { name: GigabitEthernet1, description: \"to spine1 Gi1\", uplink: true }","  - { name: GigabitEthernet2, description: \"host1\" }"],"title":"inventory/host_vars/leaf1.yml"},"hot":["data","gi1","gi2"],"text":"leaf1's ports are a list in its host file: a name, a description, and `uplink: true` on the uplink.","title":"The ports are data."},{"code":{"hl":[3,6],"lines":["- name: Description and no shutdown, one port at a time","  cisco.ios.ios_interfaces:","    config:","      - name: \"{{ item.name }}\"","        description: \"{{ item.description }}\"","        enabled: true","  loop: \"{{ interfaces }}\""],"title":"one task"},"dim":["gi2"],"hot":["gi1"],"packets":[{"label":"item 1","path":["gi1","leaf1"]}],"table":{"cols":["item","description","jumbo MTU"],"hl":0,"rows":[["GigabitEthernet1","to spine1 Gi1",""],["GigabitEthernet2","",""]],"title":"ios_interfaces on leaf1, per item"},"text":"`item` is the current entry, so `{{ item.name }}` is `GigabitEthernet1` the first time round.","title":"loop: the first item."},{"dim":["gi1"],"hot":["gi2"],"packets":[{"label":"item 2","path":["gi2","leaf1"]}],"table":{"cols":["item","description","jumbo MTU"],"hl":1,"rows":[["GigabitEthernet1","to spine1 Gi1",""],["GigabitEthernet2","host1",""]],"title":"ios_interfaces on leaf1, per item"},"text":"Second time round, `item` is GigabitEthernet2. One task, every port, no port names in the playbook.","title":"The same task, the next item."},{"code":{"hl":[6],"lines":["- name: Jumbo MTU on uplinks only","  cisco.ios.ios_interfaces:","    config:","      - name: \"{{ item.name }}\"","        mtu: 9100","  loop: \"{{ interfaces }}\"","  when: item.uplink | default(false)"],"title":"the MTU task"},"hot":["gi1"],"packets":[{"label":"mtu 9100","path":["gi1","leaf1"]},{"end":"drop","label":"skipping","path":["gi2","leaf1"]}],"table":{"cols":["item","description","jumbo MTU"],"rows":[["GigabitEthernet1","to spine1 Gi1","9100"],["GigabitEthernet2","host1","skipping"]],"title":"ios_interfaces on leaf1, per item"},"text":"The MTU task loops again. `when: item.uplink | default(false)` is true for Gi1 and false for Gi2, which shows `skipping`.","title":"when: the uplink only."},{"code":{"hl":[0,2],"lines":["{% for sw in groups['fabric'] | sort %}","{% set h = hostvars[sw] %}","| {{ sw }} | {{ 'spine' if sw in groups['spines'] else 'leaf' }} | {{ h.sw_version }} | {{ h.location }} |","{% endfor %}"],"title":"fabric-report.md.j2"},"dim":["leaf1"],"hot":["rep"],"packets":[{"c":"green","label":"template","path":["data","rep"]}],"show":["rep"],"table":{"cols":["Switch","Role","Version","Location"],"rows":[["leaf1","leaf","0.1.2","Row A, rack 2"],["leaf2","leaf","0.1.2","Row A, rack 3"],["spine1","spine","0.1.2","Row A, rack 1"]],"title":"build/fabric-report.md"},"text":"A template loops over `groups['fabric']` and reads each switch's `hostvars`. Out comes Markdown you could paste into a wiki.","title":"The same data, into a report."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<hr>
<h2 id="templates-data-into-any-text">Templates: data into any text</h2>
<p>Loops and conditionals produce config. <strong>Templates</strong> produce <em>anything</em>: a config file for a device that
doesn&rsquo;t have an API, a CSV, an email body, or a report. Ansible uses Jinja2, the same <code>{{ }}</code> syntax you&rsquo;ve
been using, plus <code>{% %}</code> for logic.</p>
<p>Here&rsquo;s the lab&rsquo;s fabric report template:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-jinja" data-lang="jinja"><span class="line"><span class="cl"><span class="x">| Switch | Role | Version | Location |
</span></span></span><span class="line"><span class="cl"><span class="x">|---|---|---|---|
</span></span></span><span class="line"><span class="cl"><span class="x"></span><span class="cp">{%</span> <span class="k">for</span> <span class="nv">sw</span> <span class="k">in</span> <span class="nv">groups</span><span class="o">[</span><span class="s1">&#39;fabric&#39;</span><span class="o">]</span> <span class="o">|</span> <span class="nf">sort</span> <span class="cp">%}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x"></span><span class="cp">{%</span> <span class="k">set</span> <span class="nv">h</span> <span class="o">=</span> <span class="nv">hostvars</span><span class="o">[</span><span class="nv">sw</span><span class="o">]</span> <span class="cp">%}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">| </span><span class="cp">{{</span> <span class="nv">sw</span> <span class="cp">}}</span><span class="x"> | </span><span class="cp">{{</span> <span class="s1">&#39;spine&#39;</span> <span class="k">if</span> <span class="nv">sw</span> <span class="k">in</span> <span class="nv">groups</span><span class="o">[</span><span class="s1">&#39;spines&#39;</span><span class="o">]</span> <span class="k">else</span> <span class="s1">&#39;leaf&#39;</span> <span class="cp">}}</span><span class="x"> | </span><span class="cp">{{</span> <span class="nv">h.sw_version</span> <span class="cp">}}</span><span class="x"> | </span><span class="cp">{{</span> <span class="nv">h.location</span> <span class="cp">}}</span><span class="x"> |
</span></span></span><span class="line"><span class="cl"><span class="x"></span><span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">## Ports
</span></span></span><span class="line"><span class="cl"><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x"></span><span class="cp">{%</span> <span class="k">for</span> <span class="nv">sw</span> <span class="k">in</span> <span class="nv">groups</span><span class="o">[</span><span class="s1">&#39;fabric&#39;</span><span class="o">]</span> <span class="o">|</span> <span class="nf">sort</span> <span class="cp">%}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">### </span><span class="cp">{{</span> <span class="nv">sw</span> <span class="cp">}}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x"></span><span class="cp">{%</span> <span class="k">for</span> <span class="nv">i</span> <span class="k">in</span> <span class="nv">hostvars</span><span class="o">[</span><span class="nv">sw</span><span class="o">]</span><span class="nv">.interfaces</span> <span class="cp">%}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">- `</span><span class="cp">{{</span> <span class="nv">i.name</span> <span class="cp">}}</span><span class="x">` </span><span class="cp">{{</span> <span class="nv">i.description</span> <span class="cp">}}{%</span> <span class="k">if</span> <span class="nv">i.uplink</span> <span class="o">|</span> <span class="nf">default</span><span class="o">(</span><span class="kp">false</span><span class="o">)</span> <span class="cp">%}</span><span class="x"> **(uplink)**</span><span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x"></span><span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x">
</span></span></span><span class="line"><span class="cl"><span class="x"></span><span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span><span class="x">
</span></span></span></code></pre></div><p>The new ideas:</p>
<ul>
<li><strong><code>{% for %}</code> / <code>{% endfor %}</code></strong> loops, inside the template instead of on the task.</li>
<li><strong><code>{% if %}</code></strong> is the template&rsquo;s <code>when</code>.</li>
<li><strong><code>groups['fabric']</code></strong> is the list of every host in the group, and <strong><code>hostvars[sw]</code></strong> is any other host&rsquo;s
variables. That&rsquo;s what lets one template describe the whole fabric, not just the current switch.</li>
</ul>
<p>The playbook that renders it has two plays: the first runs <code>ios_facts</code> on every switch and keeps its version
(so <code>sw_version</code> exists in <code>hostvars</code>), the second runs once on <code>localhost</code> and writes the file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl">- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Write the report</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">hosts</span><span class="p">:</span><span class="w"> </span><span class="l">localhost</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">gather_facts</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">connection</span><span class="p">:</span><span class="w"> </span><span class="l">local</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">tasks</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Render build/fabric-report.md</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">ansible.builtin.template</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">src</span><span class="p">:</span><span class="w"> </span><span class="l">fabric-report.md.j2     </span><span class="w"> </span><span class="c"># Ansible looks in playbooks/templates/ for you</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">dest</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ playbook_dir }}/../build/fabric-report.md&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">mode</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;0644&#34;</span><span class="w">
</span></span></span></code></pre></div><p>The result is a Markdown file you could paste straight into a wiki:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">| Switch | Role | Version | Location |
</span></span><span class="line"><span class="cl">|---|---|---|---|
</span></span><span class="line"><span class="cl">| leaf1 | leaf | 0.1.2 | Row A, rack 2 |
</span></span><span class="line"><span class="cl">| leaf2 | leaf | 0.1.2 | Row A, rack 3 |
</span></span><span class="line"><span class="cl">| spine1 | spine | 0.1.2 | Row A, rack 1 |
</span></span></code></pre></div><hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-templates-full-of-logic">1. Templates full of logic</h3>
<p>A template with nested <code>if</code>s, string surgery and twenty <code>set</code> statements is a program written in the worst
language available. When a template gets clever, move the cleverness into the data (a better-shaped variable)
or into a filter, and keep the template mostly <code>{{ }}</code>.</p>
<h3 id="2-whitespace-surprises">2. Whitespace surprises</h3>
<p>Jinja2 in Ansible trims the newline after a <code>{% %}</code> tag, which is usually what you want and occasionally
eats a blank line you needed. My first version of that report ran every switch&rsquo;s heading straight into the
previous bullet list. The fix was one empty line after the inner <code>{% endfor %}</code>. When a template&rsquo;s output looks
squashed, look at the blank lines around your tags first.</p>
<h3 id="3-looping-where-one-call-would-do">3. Looping where one call would do</h3>
<p>Loops are the right first tool. But a loop over 48 ports is 48 round trips and 48 lines of output per switch.
When you know it works, build the list in one go (a <code>map</code> filter, or the data as it already is) and pass it in
one call.</p>
<h3 id="4-templating-whole-configs-when-a-module-would-do">4. Templating whole configs when a module would do</h3>
<p>It&rsquo;s tempting to render a switch&rsquo;s entire config from a template and push it. That&rsquo;s a real strategy (full
config replace), but it&rsquo;s a different one: you take on the diffing, the ordering and every default that does
or doesn&rsquo;t print. For the things resource modules cover, like ports and NTP, let the module compare data with
the running config. Reach for config templates when you&rsquo;ve decided to own the whole file.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/ansible-101/#chapter-4">Chapter 4 of the lab</a> lists the leaves&rsquo; ports as data, brings every port up with
one looped task, gives only the uplinks a jumbo MTU, and finishes the template for the fabric report.</p>
<p>Next, in <a href="/lessons/ansible-101/handlers-tags-errors/">lesson 5</a>, we save the config only when something actually
changed, run part of a playbook with tags, and recover cleanly when a change fails halfway through.</p>
]]></content:encoded></item><item><title>Ansible group_vars, host_vars and Facts for Networks (Ansible 101 for Networking, Lesson 3)</title><link>https://networkdoodles.com/lessons/ansible-101/variables-and-facts/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/variables-and-facts/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>capeos</category><category>howto</category><description>Stop hard-coding values in playbooks: group_vars and host_vars, the three precedence rules that matter, and reading switch facts with register and set_fact.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>The playbook from <a href="/lessons/ansible-101/first-playbook/">lesson 2</a> works, but it has a problem you&rsquo;ll recognize
from every config template you&rsquo;ve ever inherited: the values are baked in. The banner text, the contact
address and the domain are all typed straight into the task. The day leaf1 needs a different value, you copy
the playbook, and now you have two.</p>
<p>This lesson pulls the data out of the playbook and into <strong>variables</strong>: per group, per host, with clear rules for
which one wins. Then we flip the direction and ask the switches for <strong>facts</strong>, values we read instead of
write.</p>
<hr>
<h2 id="the-rule-playbooks-describe-how-inventory-describes-what">The rule: playbooks describe how, inventory describes what</h2>
<p>Here&rsquo;s the split I push every team toward:</p>
<ul>
<li><strong>The playbook</strong> says <em>how</em>: &ldquo;configure NTP from the list of servers&rdquo;, &ldquo;set the location from the switch&rsquo;s
location&rdquo;.</li>
<li><strong>The inventory</strong> says <em>what</em>: which NTP servers, which location, per group and per host.</li>
</ul>
<p>A playbook written this way never names a switch and never contains an IP address. Add a site, a switch or an
NTP server, and you change data, not code. That&rsquo;s what lets one playbook run safely against a lab, staging and
production: same how, different what.</p>
<hr>
<h2 id="group_vars-and-host_vars">group_vars and host_vars</h2>
<p>Ansible looks for variables in two folders, named after the groups and hosts in your inventory:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">inventory/
</span></span><span class="line"><span class="cl">├── hosts.yml
</span></span><span class="line"><span class="cl">├── group_vars/
</span></span><span class="line"><span class="cl">│   └── fabric.yml        ← every host in the fabric group
</span></span><span class="line"><span class="cl">└── host_vars/
</span></span><span class="line"><span class="cl">    ├── spine1.yml        ← spine1 only
</span></span><span class="line"><span class="cl">    ├── leaf1.yml
</span></span><span class="line"><span class="cl">    └── leaf2.yml
</span></span></code></pre></div><p>The file name <em>is</em> the link. <code>group_vars/fabric.yml</code> applies to every member of <code>fabric</code>, which is every
switch. <code>host_vars/leaf1.yml</code> applies to leaf1 alone. No configuration ties them together; Ansible matches the
names.</p>
<p>First, the connection settings from lesson 1 move out of the inventory and into <code>group_vars/fabric.yml</code>, where
they belong. The inventory goes back to doing one job, listing hosts and groups:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># inventory/group_vars/fabric.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible_connection</span><span class="p">:</span><span class="w"> </span><span class="l">ansible.netcommon.network_cli</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible_network_os</span><span class="p">:</span><span class="w"> </span><span class="l">cisco.ios.ios</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible_user</span><span class="p">:</span><span class="w"> </span><span class="l">admin</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ansible_password</span><span class="p">:</span><span class="w"> </span><span class="l">capeos-lab           </span><span class="w"> </span><span class="c"># chapter 7 moves this into a vault</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">ntp_servers</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">server</span><span class="p">:</span><span class="w"> </span><span class="m">162.159.200.1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">server</span><span class="p">:</span><span class="w"> </span><span class="m">162.159.200.123</span><span class="w">
</span></span></span></code></pre></div><p>Notice the shape of <code>ntp_servers</code>: a list of objects with a <code>server</code> key, not a list of bare IPs. That&rsquo;s on
purpose. It&rsquo;s the shape the <code>cisco.ios.ios_ntp_global</code> module takes for its servers, so the playbook can hand
the list over as is. When you get to choose how your data looks, shape it like the thing that consumes it.</p>
<p>Each switch&rsquo;s own facts go in its host file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># inventory/host_vars/leaf1.yml</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="nt">location</span><span class="p">:</span><span class="w"> </span><span class="l">Row A, rack 2</span><span class="w">
</span></span></span></code></pre></div><h3 id="where-ansible-actually-looks">Where Ansible actually looks</h3>
<p>This bit me while building the lab. Ansible loads <code>group_vars/</code> and <code>host_vars/</code> from <strong>next to the inventory
file</strong> and <strong>next to the playbook</strong>. Not from the folder you run it in, and not from the repo root. I had them
at the top of the repo, the connection settings never loaded, and Ansible tried to SSH into the switches as if
they were Linux servers. The error mentioned temporary directories and never once mentioned variables.</p>
<p>If your variables seem to be ignored, check where the folders are first. Keeping them inside <code>inventory/</code> is
the layout that never surprises anyone.</p>
<hr>
<h2 id="one-playbook-three-different-switches">One playbook, three different switches</h2>
<p>Now the playbook only refers to variable names:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl">- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Base config</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">hosts</span><span class="p">:</span><span class="w"> </span><span class="l">fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">gather_facts</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">tasks</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">NTP servers, from group_vars</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_ntp_global</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">servers</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ ntp_servers }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Where the switch lives, from host_vars</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">lines</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="s2">&#34;snmp-server location {{ location }}&#34;</span><span class="w">
</span></span></span></code></pre></div><p>The <code>{{ }}</code> is Jinja2, Ansible&rsquo;s templating language. <code>{{ location }}</code> means &ldquo;this host&rsquo;s value of
<code>location</code>&rdquo;, so the same task sends <code>snmp-server location Row A, rack 1</code> to spine1 and
<code>snmp-server location Row A, rack 2</code> to leaf1. Quote any value that starts with <code>{{</code>; otherwise YAML thinks
you&rsquo;re starting a dictionary and the error message is no help at all. (Quoting the whole line, as here, is the
habit that saves you from ever having to think about it.)</p>
<p>The two tasks use two kinds of module. The location is one config line, so it&rsquo;s <code>ios_config</code> from lesson 2,
with the variable inside the line. NTP uses a <strong>resource module</strong>, <code>ios_ntp_global</code>: it takes structured data
instead of lines, reads the switch&rsquo;s NTP config into the same structure, compares the two, and sends only
what&rsquo;s missing. Two servers or ten, the task doesn&rsquo;t change. That&rsquo;s why the shape of <code>ntp_servers</code> mattered.</p>
<hr>
<h2 id="which-value-wins">Which value wins</h2>
<p>Ansible has twenty-two levels of variable precedence. You need three of them:</p>
<ol>
<li><strong>Host beats group.</strong> A value in <code>host_vars/leaf1.yml</code> beats the same name in <code>group_vars/fabric.yml</code>.
This is how you handle the exception without forking the playbook: put the default on the group, the
exception on the host.</li>
<li><strong>Specific group beats general group.</strong> <code>group_vars/leaves.yml</code> beats <code>group_vars/fabric.yml</code> beats
<code>group_vars/all.yml</code>, because <code>leaves</code> is a child of <code>fabric</code>, which is a child of <code>all</code>.</li>
<li><strong>Extra vars (<code>-e</code>) beat everything.</strong> <code>ansible-playbook site.yml -e location=&quot;Lab bench&quot;</code> overrides every
file. Useful for a one-off; dangerous as a habit, because the value lives in someone&rsquo;s shell history
instead of in Git.</li>
</ol>
<p>There&rsquo;s a fourth you&rsquo;ll meet in lesson 6: <strong>role defaults lose to everything</strong>, which is exactly what makes them
useful.</p>
<p>When you&rsquo;re not sure what a host will get, ask Ansible instead of guessing:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">ansible-inventory --host leaf1
</span></span></code></pre></div><p>That prints every variable leaf1 ends up with, after all the merging. It&rsquo;s the fastest way to settle an
argument about precedence.</p>

<figure class="netsim" data-netsim tabindex="0" aria-label="Variables reaching three switches: ntp_servers from group_vars/fabric.yml goes to all of them, each location comes from its own host_vars file, an extra var on the command line overrides every file for one run, and ansible-inventory shows the merged result. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="Variables reaching three switches: ntp_servers from group_vars/fabric.yml goes to all of them, each location comes from its own host_vars file, an extra var on the command line overrides every file for one run, and ansible-inventory shows the merged result"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":340,"links":[],"narrow":{"at":{"ex":[180,185,230],"fab":[70,60],"hv":[250,60],"leaf1":[180,310],"leaf2":[300,310],"spine1":[60,310]},"h":400,"w":360},"nodes":{"ex":{"c":"amber","h":44,"hidden":true,"kind":"box","label":"extra vars (-e)","sub":"location=\"Lab bench\"","w":210,"x":120,"y":290},"fab":{"kind":"file","label":"fabric.yml","sub":"group_vars/","x":110,"y":60},"hv":{"kind":"file","label":"host_vars/","sub":"one file per switch","x":110,"y":175},"leaf1":{"kind":"switch","label":"leaf1","sub":"leaves","x":620,"y":170},"leaf2":{"kind":"switch","label":"leaf2","sub":"leaves","x":620,"y":275},"spine1":{"kind":"switch","label":"spine1","sub":"spines","x":620,"y":65}},"steps":[{"hot":["fab"],"packets":[{"label":"ntp_servers","path":["fab","spine1"]},{"label":"ntp_servers","path":["fab","leaf1"]},{"label":"ntp_servers","path":["fab","leaf2"]}],"table":{"cols":["host","ntp_servers","location"],"rows":[["spine1","2 servers (fabric.yml)","not set"],["leaf1","2 servers (fabric.yml)","not set"],["leaf2","2 servers (fabric.yml)","not set"]],"title":"what each switch gets"},"text":"The file name is the link. Every host in `fabric` gets `ntp_servers`, so all three get the same two servers.","title":"group_vars/fabric.yml: every switch."},{"hot":["hv"],"packets":[{"label":"location","path":["hv","spine1"]},{"label":"location","path":["hv","leaf1"]},{"label":"location","path":["hv","leaf2"]}],"set":{"leaf1":"Row A, rack 2","leaf2":"Row A, rack 3","spine1":"Row A, rack 1"},"table":{"cols":["host","ntp_servers","location"],"rows":[["spine1","2 servers (fabric.yml)","Row A, rack 1 (host_vars)"],["leaf1","2 servers (fabric.yml)","Row A, rack 2 (host_vars)"],["leaf2","2 servers (fabric.yml)","Row A, rack 3 (host_vars)"]],"title":"what each switch gets"},"text":"`host_vars/leaf1.yml` applies to leaf1 and nothing else. Each switch gets its own `location`.","title":"host_vars/: what's one switch's alone."},{"code":{"hl":[0],"lines":["- \"snmp-server location {{ location }}\"","","# spine1: snmp-server location Row A, rack 1","# leaf1:  snmp-server location Row A, rack 2","# leaf2:  snmp-server location Row A, rack 3"],"title":"what the task sends"},"hot":["spine1","leaf1","leaf2"],"text":"`{{ location }}` is this host's value, so the same task sends a different line to each switch.","title":"One task, three different lines."},{"code":null,"hot":["ex"],"packets":[{"c":"amber","label":"Lab bench","path":["ex","spine1"]},{"c":"amber","label":"Lab bench","path":["ex","leaf1"]},{"c":"amber","label":"Lab bench","path":["ex","leaf2"]}],"set":{"leaf1":"Lab bench","leaf2":"Lab bench","spine1":"Lab bench"},"show":["ex"],"table":{"cols":["host","ntp_servers","location"],"rows":[["spine1","2 servers (fabric.yml)","Lab bench (-e)"],["leaf1","2 servers (fabric.yml)","Lab bench (-e)"],["leaf2","2 servers (fabric.yml)","Lab bench (-e)"]],"title":"what each switch gets"},"text":"`-e location=\"Lab bench\"` overrides host_vars and group_vars alike, for this one run.","title":"Extra vars beat every file."},{"hide":["ex"],"hot":["hv"],"set":{"leaf1":"Row A, rack 2","leaf2":"Row A, rack 3","spine1":"Row A, rack 1"},"table":{"cols":["host","ntp_servers","location"],"rows":[["spine1","2 servers (fabric.yml)","Row A, rack 1 (host_vars)"],["leaf1","2 servers (fabric.yml)","Row A, rack 2 (host_vars)"],["leaf2","2 servers (fabric.yml)","Row A, rack 3 (host_vars)"]],"title":"what each switch gets"},"text":"The override lived in someone's shell history, not in Git. Useful for a one-off, dangerous as a habit.","title":"Drop the -e and the files decide again."},{"code":{"hl":[0],"lines":["ansible-inventory --host leaf1"],"title":"ask, don't guess"},"dim":["spine1","leaf2"],"hot":["leaf1"],"table":{"cols":["variable","value","set in"],"rows":[["ansible_connection","ansible.netcommon.network_cli","group_vars/fabric.yml"],["ntp_servers","162.159.200.1, 162.159.200.123","group_vars/fabric.yml"],["location","Row A, rack 2","host_vars/leaf1.yml"]],"title":"leaf1's variables"},"text":"`ansible-inventory --host leaf1` prints every variable leaf1 gets, after all the merging.","title":"Ask Ansible what a host ends up with."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<hr>
<h2 id="facts-reading-instead-of-writing">Facts: reading instead of writing</h2>
<p>Variables are what <em>you</em> say. <strong>Facts</strong> are what the <em>device</em> says. On servers, Ansible gathers facts
automatically at the start of each play. On network devices we turned that off in lesson 1, and we ask
explicitly instead, with the platform&rsquo;s own <strong>facts module</strong>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl">- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">What the switches say about themselves</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">hosts</span><span class="p">:</span><span class="w"> </span><span class="l">fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">gather_facts</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">tasks</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Gather the switch&#39;s facts</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_facts</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">gather_subset</span><span class="p">:</span><span class="w"> </span><span class="l">min</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Keep the two facts we care about</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">ansible.builtin.set_fact</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">sw_version</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ ansible_facts.net_version }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">sw_serial</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ ansible_facts.net_serialnum }}&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Show them</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">ansible.builtin.debug</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">msg</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;{{ inventory_hostname }} runs {{ sw_version }}, serial {{ sw_serial }}&#34;</span><span class="w">
</span></span></span></code></pre></div><p>A facts module is the difference between scraping and asking. In lesson 1 you ran <code>show version</code> and read the
answer yourself. <code>ios_facts</code> runs the show commands for you, parses the output, and hands back data:
<code>net_version</code>, <code>net_serialnum</code>, <code>net_hostname</code>, <code>net_image</code>. Those land in <strong><code>ansible_facts</code></strong>, for that
host, for the rest of the play. <code>gather_subset: min</code> asks for the basics and nothing more.</p>
<p>Then two keywords do the rest:</p>
<ul>
<li><strong><code>set_fact</code></strong> creates new variables for this host, here under shorter names that read better later.
Variables made this way are called facts too.</li>
<li><strong><code>debug</code></strong> prints. It&rsquo;s the <code>print()</code> of Ansible, and you&rsquo;ll use it more than you&rsquo;d like to admit.</li>
</ul>
<p>On leaf1 the last task prints:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">msg: leaf1 runs 0.1.2, serial CAPEQ3I7EKD
</span></span></code></pre></div><p>(It&rsquo;s a lab switch, so the serial is a made-up placeholder.)</p>
<p>When the value you want isn&rsquo;t a fact, any task&rsquo;s result can be kept: <strong><code>register: something</code></strong> saves the
module&rsquo;s whole return value in a variable. Lesson 5 uses it to read a port&rsquo;s config back after a change.</p>
<p>The lab&rsquo;s version also writes those facts to a file per switch with the <code>copy</code> module. Because that file
belongs on <em>your</em> machine and not the switch, the task runs with <code>delegate_to: localhost</code>. Remember that
pattern: any time a task should run on the control node instead of the device, delegate it.</p>
<hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-variables-everywhere">1. Variables everywhere</h3>
<p>Vars in the play, vars in the inventory, vars in <code>group_vars</code>, a <code>vars_files</code> list, and <code>-e</code> in the run
script. Ansible allows all of it; your teammates can&rsquo;t follow it. Pick two places, <code>group_vars</code> and
<code>host_vars</code>, and keep values there unless you have a reason.</p>
<h3 id="2-same-variable-different-meanings">2. Same variable, different meanings</h3>
<p><code>vlan</code> meaning a VLAN ID in one playbook and a VLAN name in another. <code>servers</code> meaning NTP in one file and
syslog in the next. Name variables for what they are: <code>ntp_servers</code>, <code>syslog_servers</code>, <code>mgmt_vlan_id</code>. Lesson 6
adds a prefix rule for roles that makes this automatic.</p>
<h3 id="3-data-shaped-for-humans-not-for-the-device">3. Data shaped for humans, not for the device</h3>
<p>A list of IPs when the module wants a list of objects, a comma-separated string when it wants a list. Every
mismatch becomes Jinja gymnastics in the playbook. Shape the data like the module it feeds, and the playbook
stays boring, which is what you want from a playbook.</p>
<h3 id="4-gathering-every-fact-every-run">4. Gathering every fact, every run</h3>
<p><code>gather_subset: all</code> runs a pile of show commands on every switch, every time. It works, it&rsquo;s slow, and it&rsquo;s a
lot of data to dig through. Ask for the subset you need, like the playbook above does.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/ansible-101/#chapter-3">Chapter 3 of the lab</a> moves the connection settings into <code>group_vars</code>, sets NTP
and a location per switch from one playbook, then has you read each switch&rsquo;s version and serial with
<code>ios_facts</code> and write them to a file.</p>
<p>Next, in <a href="/lessons/ansible-101/loops-and-templates/">lesson 4</a>, we configure every port from a list of data,
treat uplinks differently with <code>when</code>, and render a report of the whole fabric with Jinja2.</p>
]]></content:encoded></item><item><title>Your First Ansible Playbook for Network Devices (Ansible 101 for Networking, Lesson 2)</title><link>https://networkdoodles.com/lessons/ansible-101/first-playbook/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/first-playbook/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>capeos</category><category>howto</category><description>Write an Ansible playbook that configures a whole switch fabric, read the PLAY RECAP, prove it is idempotent, and use check mode and diff as your change review.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>In <a href="/lessons/ansible-101/hello-ansible/">lesson 1</a> we pointed Ansible at three switches and asked them questions,
one ad-hoc command at a time. That&rsquo;s useful, but it&rsquo;s still you typing commands. The moment you want to make
the same change everywhere, review it before it happens, and run it again next month without thinking, you
want a <strong>playbook</strong>.</p>
<p>This lesson covers what one looks like, what a run tells you, and the two things that separate automation from
a fancy SSH loop: proving a second run changes nothing, and previewing a change before you make it.</p>
<hr>
<h2 id="anatomy-of-a-playbook">Anatomy of a playbook</h2>
<p>Here&rsquo;s a whole one. It sets the contact and the login banner on every switch in the fabric:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nn">---</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Hello, fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">hosts</span><span class="p">:</span><span class="w"> </span><span class="l">fabric</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">gather_facts</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">tasks</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Who to call</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_config</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">lines</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="l">snmp-server contact netops@networkdoodles.com</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span>- <span class="nt">name</span><span class="p">:</span><span class="w"> </span><span class="l">Login banner</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">cisco.ios.ios_banner</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">banner</span><span class="p">:</span><span class="w"> </span><span class="l">login</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">text</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;Managed by Ansible - Network Doodles lab&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">state</span><span class="p">:</span><span class="w"> </span><span class="l">present</span><span class="w">
</span></span></span></code></pre></div><p>Three layers, and once you see them you&rsquo;ll see them everywhere:</p>
<table>
  <thead>
      <tr>
          <th>Layer</th>
          <th>Here</th>
          <th>What it means</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>Playbook</strong></td>
          <td>the file</td>
          <td>A list of plays, run top to bottom</td>
      </tr>
      <tr>
          <td><strong>Play</strong></td>
          <td><code>- name: Hello, fabric</code></td>
          <td><em>Which hosts</em>, plus the tasks to run on them</td>
      </tr>
      <tr>
          <td><strong>Task</strong></td>
          <td><code>- name: Who to call</code></td>
          <td>One call to one module, with arguments</td>
      </tr>
  </tbody>
</table>
<p>The play&rsquo;s <code>hosts: fabric</code> uses the same patterns as ad-hoc commands, so <code>leaves</code>, <code>leaf1</code> or
<code>fabric:!spines</code> all work. <code>gather_facts: false</code> is there because, as we saw in lesson 1, there&rsquo;s no Python on a
switch to gather facts with.</p>
<p>The first task calls <strong><code>cisco.ios.ios_config</code></strong>, the module that adds configuration lines. You give it the
lines as you&rsquo;d type them in config mode. Before it sends anything, it reads the switch&rsquo;s running config and
checks whether each line is already there. Lines that are present are left alone; only the missing ones get
sent. So the task describes a line that should be in the config, and the module decides whether to type it.</p>
<p>The second task uses a different module, because a banner isn&rsquo;t one config line. It&rsquo;s a block of text between
two delimiters, which a line-by-line comparison can&rsquo;t handle reliably. <code>cisco.ios.ios_banner</code> knows what a
banner looks like on the switch and compares the text itself.</p>
<p>Always name your tasks. The name is what shows up in the output, in the CI log, and in the 2am message from
whoever ran it. &ldquo;Who to call&rdquo; tells you what happened; an unnamed task tells you which module ran.</p>
<h3 id="lines-exactly-as-the-switch-prints-them">Lines, exactly as the switch prints them</h3>
<p><code>ios_config</code> compares <strong>text</strong>. It doesn&rsquo;t know what <code>snmp-server contact</code> means; it knows whether that string
appears in the running config. That has one big consequence: write each line the way <code>show running-config</code>
prints it, not the way you&rsquo;d abbreviate it at the prompt.</p>
<p>At the prompt, IOS-style CLIs are forgiving: they accept shortcuts and store the long form, so <code>int gi1</code>
becomes <code>interface GigabitEthernet1</code> in the running config. A playbook gets no such forgiveness. Write a
line in any form other than the one the switch prints (<code>snmp contact</code> where it prints <code>snmp-server contact</code>)
and <code>ios_config</code> never finds it in the running config. If the switch accepts the short form, the module sends
it again on every run and reports <code>changed</code> every time. It reminds you of this whenever it changes something:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">[WARNING]: To ensure idempotency and correct diff the input configuration lines should be
</span></span><span class="line"><span class="cl">similar to how they appear if present in the running configuration on device
</span></span></code></pre></div><p>The same rule explains a trap you&rsquo;ll meet in lesson 4: a port that&rsquo;s up has <strong>no</strong> <code>no shutdown</code> line in the
running config, so a playbook that lists <code>no shutdown</code> would never find it there.</p>
<p>That&rsquo;s the trade-off of CLI-based config modules:</p>
<table>
  <thead>
      <tr>
          <th></th>
          <th>CLI config modules (<code>ios_config</code>)</th>
          <th>Model-driven APIs (NETCONF, gNMI, JSON-RPC)</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>What you write</td>
          <td>Config lines you already know</td>
          <td>Paths and values in the device&rsquo;s data model</td>
      </tr>
      <tr>
          <td>How it compares</td>
          <td>Text lines against the running config</td>
          <td>Structured data; the device works out the difference</td>
      </tr>
      <tr>
          <td>Works on</td>
          <td>Anything with a CLI Ansible can drive</td>
          <td>Platforms that have the API</td>
      </tr>
      <tr>
          <td>Where it bites</td>
          <td>Abbreviations, defaults that don&rsquo;t print, ordering</td>
          <td>Learning the data model; less readable for humans</td>
      </tr>
  </tbody>
</table>
<p>Neither is wrong. A CLI module is the fastest route from &ldquo;I know the command&rdquo; to &ldquo;it&rsquo;s automated&rdquo;, and every
line in the playbook is one you can check by hand. You just own the exact text. In between sit the
<strong>resource modules</strong> (<code>ios_ntp_global</code>, <code>ios_interfaces</code>), which take structured data and parse the running
config into the same structure before comparing. You&rsquo;ll use those from lesson 3 on, for the things a plain line
compares badly.</p>
<hr>
<h2 id="what-a-run-looks-like">What a run looks like</h2>
<p><code>ansible-playbook playbooks/hello.yml</code> runs it. The first time, against switches that don&rsquo;t have the contact
yet, the first task looks like this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">TASK [Who to call] *********************************************
</span></span><span class="line"><span class="cl">[WARNING]: To ensure idempotency and correct diff the input configuration lines should be
</span></span><span class="line"><span class="cl">similar to how they appear if present in the running configuration on device
</span></span><span class="line"><span class="cl">changed: [spine1]
</span></span><span class="line"><span class="cl">changed: [leaf1]
</span></span><span class="line"><span class="cl">changed: [leaf2]
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">PLAY RECAP *****************************************************
</span></span><span class="line"><span class="cl">leaf1    : ok=1    changed=1    unreachable=0    failed=0 ...
</span></span><span class="line"><span class="cl">leaf2    : ok=1    changed=1    unreachable=0    failed=0 ...
</span></span><span class="line"><span class="cl">spine1   : ok=1    changed=1    unreachable=0    failed=0 ...
</span></span></code></pre></div><p>The <strong>PLAY RECAP</strong> is the most important part of any run, and the part people scroll past. Read it first,
every time:</p>
<ul>
<li><strong><code>ok</code></strong> tasks found things already as described, or made them so.</li>
<li><strong><code>changed</code></strong> tasks actually changed something on the device.</li>
<li><strong><code>failed</code></strong> and <strong><code>unreachable</code></strong> are the ones that need you. If either is non-zero, scroll up to the first
red <code>fatal:</code> line; it names the task and the reason.</li>
</ul>
<p>The hosts don&rsquo;t always finish in the same order. Ansible works on several hosts at once (five by default), so
the switches that answer first finish first. That&rsquo;s a feature, and it&rsquo;s why your tasks should never depend on
the order hosts run in.</p>
<hr>
<h2 id="the-second-run">The second run</h2>
<p>Run the same playbook again and every task says <code>ok</code>, the recap says <code>changed=0</code>, and the warning is gone. The
module read each switch&rsquo;s running config, found every line already there, and sent nothing. That&rsquo;s
<strong>idempotency</strong>, and it&rsquo;s the single most important property of a good playbook.</p>
<p>It&rsquo;s what lets you run the same playbook daily, from a pipeline, against a hundred switches, and have it
change exactly the ones that drifted. A playbook that reports <code>changed</code> on every run is lying to you about
what it did, and you lose the ability to tell a real change from noise. With <code>ios_config</code>, the usual liar is a
line that isn&rsquo;t written the way the switch prints it.</p>

<figure class="netsim" data-netsim tabindex="0" aria-label="The ios_config task on its first run reads each running config, finds the contact line missing and sends it (changed); on the second run it finds the line and sends nothing (ok); check mode does the same comparison and stops before sending. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="The ios_config task on its first run reads each running config, finds the contact line missing and sends it (changed); on the second run it finds the line and sends nothing (ok); check mode does the same comparison and stops before sending"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":340,"links":[["pb","mod"],["mod","spine1"],["mod","leaf1"],["mod","leaf2"]],"narrow":{"at":{"leaf1":[180,290],"leaf2":[300,290],"mod":[270,70],"pb":[80,70],"spine1":[60,290]},"h":380,"w":360},"nodes":{"leaf1":{"kind":"switch","label":"leaf1","sub":"no contact","x":620,"y":170},"leaf2":{"kind":"switch","label":"leaf2","sub":"no contact","x":620,"y":275},"mod":{"kind":"gear","label":"ios_config","sub":"compares text","x":320,"y":170},"pb":{"kind":"file","label":"hello.yml","sub":"task: Who to call","x":90,"y":170},"spine1":{"kind":"switch","label":"spine1","sub":"no contact","x":620,"y":65}},"steps":[{"code":{"hl":[3],"lines":["- name: Who to call","  cisco.ios.ios_config:","    lines:","      - snmp-server contact netops@networkdoodles.com"],"title":"playbooks/hello.yml"},"hot":["pb","mod"],"links":[["pb","mod"]],"text":"Written exactly as `show running-config` prints it. The module decides whether to type it.","title":"The task describes one line."},{"hot":["mod"],"packets":[{"label":"running-config","path":["spine1","mod"]},{"label":"running-config","path":["leaf1","mod"]},{"label":"running-config","path":["leaf2","mod"]}],"say":{"mod":"contact line?\nnot there"},"text":"Before sending anything, the module reads each switch's running config and looks for that exact string.","title":"First, read the running config."},{"hot":["spine1","leaf1","leaf2"],"packets":[{"c":"amber","label":"snmp-server contact","path":["mod","spine1"]},{"c":"amber","label":"snmp-server contact","path":["mod","leaf1"]},{"c":"amber","label":"snmp-server contact","path":["mod","leaf2"]}],"set":{"leaf1":"contact set","leaf2":"contact set","spine1":"contact set"},"table":{"cols":["host","Who to call","recap"],"rows":[["leaf1","changed","changed=1"],["leaf2","changed","changed=1"],["spine1","changed","changed=1"]],"title":"PLAY RECAP"},"text":"Only the missing line goes out, on all three switches. The recap counts one `changed` task per host.","title":"Not there, so it sends it: changed."},{"good":["spine1","leaf1","leaf2"],"packets":[{"label":"running-config","path":["spine1","mod"]},{"label":"running-config","path":["leaf1","mod"]},{"label":"running-config","path":["leaf2","mod"]}],"say":{"mod":"already there:\nnothing to send"},"table":{"cols":["host","Who to call","recap"],"rows":[["leaf1","ok","changed=0"],["leaf2","ok","changed=0"],["spine1","ok","changed=0"]],"title":"PLAY RECAP"},"text":"Same comparison, the line is found, the module sends nothing. `changed=0` is idempotency.","title":"The second run: already there, nothing sent."},{"code":{"hl":[3,4],"lines":["TASK [The domain the switches live in] ****","changed: [leaf1] =\u003e","    changed: true","    commands:","    - ip domain name lab.networkdoodles.com"],"title":"--check -v"},"hot":["mod","leaf1"],"packets":[{"label":"running-config","path":["leaf1","mod"]}],"say":{"mod":"would send 1 line,\nsent nothing"},"table":null,"text":"A new task, run with `--check -v`. Ansible reads and compares, prints the commands it would type, and sends nothing.","title":"Check mode: compare, then stop."},{"code":null,"good":["spine1","leaf1","leaf2"],"packets":[{"label":"running-config","path":["spine1","mod"]},{"label":"running-config","path":["leaf1","mod"]},{"label":"running-config","path":["leaf2","mod"]}],"say":{"mod":"nothing left to do"},"text":"Run it for real, then check again: every task says `ok:` with no commands. That's your proof it landed.","title":"After the change, the same check finds nothing."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<p>When I review someone&rsquo;s automation, the first thing I do is run it twice. If the second run isn&rsquo;t
<code>changed=0</code>, we&rsquo;re not talking about anything else until it is.</p>
<hr>
<h2 id="check-mode-your-change-review">Check mode: your change review</h2>
<p>On a real network you don&rsquo;t make a change and hope. You find out what it <em>would</em> do first, and Ansible has
that built in.</p>
<p><strong><code>--check</code></strong> runs the playbook in check mode: Ansible logs in, reads the running config, works out which lines
are missing, and stops there. Nothing is sent. Add <strong><code>-v</code></strong> and each task that would change something prints
its result, including the exact commands it would type:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">TASK [The domain the switches live in] ******************************
</span></span><span class="line"><span class="cl">changed: [leaf1] =&gt;
</span></span><span class="line"><span class="cl">    banners: {}
</span></span><span class="line"><span class="cl">    changed: true
</span></span><span class="line"><span class="cl">    commands:
</span></span><span class="line"><span class="cl">    - ip domain name lab.networkdoodles.com
</span></span><span class="line"><span class="cl">    updates:
</span></span><span class="line"><span class="cl">    - ip domain name lab.networkdoodles.com
</span></span></code></pre></div><ul>
<li><strong><code>commands:</code></strong> is what it would send in config mode, on this switch, worked out from what&rsquo;s actually there.</li>
<li><strong><code>changed: true</code></strong> in check mode means &ldquo;would change&rdquo;. Nothing has, yet.</li>
<li>A task that&rsquo;s already right says <strong><code>ok:</code></strong> and has no commands.</li>
</ul>
<p>You may know <strong><code>--diff</code></strong> from server playbooks, where it shows a file&rsquo;s before and after. It&rsquo;s worth adding to
your habits, but don&rsquo;t count on it here: the <code>cisco.ios</code> modules, used the way the lab uses them, don&rsquo;t print
a line-by-line diff in check mode. On these switches, the <code>commands:</code> list from <code>-v</code> is the change review.
Platforms whose modules ask the device for a diff will show you one with <code>--diff</code>; find out which kind yours
is before you rely on it.</p>
<p>This is the part I&rsquo;d tattoo on every network team&rsquo;s change process. A check-mode run is a better change
review than any change ticket: it&rsquo;s generated from the real devices, it&rsquo;s exact, and it takes seconds. And it
works on both sides of the change. Before, it tells you what will be sent. After, the same check finds nothing
left to do, which is your proof the change landed everywhere.</p>
<hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-sending-commands-instead-of-describing-config">1. Sending commands instead of describing config</h3>
<p>Every collection has a &ldquo;send these commands&rdquo; module: <code>cisco.ios.ios_command</code>, or the generic
<code>ansible.netcommon.cli_command</code>. It&rsquo;s tempting to put <code>configure terminal</code> and your config in one and call it
done. It works once. Then it reports the same thing every run, can&rsquo;t do check mode honestly, and can&rsquo;t tell
you what&rsquo;s different, because it never looks at the running config.</p>
<p><code>ios_config</code> looks like it does the same job, since it also takes CLI lines, but it reads the running config
first and only sends what&rsquo;s missing. That&rsquo;s the difference that matters. Keep the command modules for
questions (and, in lesson 5, for the few operational commands like <code>write memory</code>).</p>
<h3 id="2-trusting-changed-from-modules-that-cant-know">2. Trusting <code>changed</code> from modules that can&rsquo;t know</h3>
<p>Related: <code>changed</code> is only as honest as the module. A config module that compares against the device is honest,
as long as you&rsquo;ve written the lines the way the device prints them. A shell or command module just reports &ldquo;I
ran something&rdquo;. If your recap says <code>changed</code> on every run, find out which task is guessing.</p>
<h3 id="3-assuming-check-mode-is-safe-everywhere">3. Assuming check mode is safe everywhere</h3>
<p><code>--check</code> is only as safe as each module&rsquo;s support for it. Well-behaved config modules skip the change and
report what they would have done. Modules that run raw commands may skip themselves entirely, or worse, run
anyway. Check mode is a superb review tool once you know your modules; it isn&rsquo;t a guarantee you can hand to
someone who doesn&rsquo;t.</p>
<h3 id="4-yaml-that-looks-right">4. YAML that looks right</h3>
<p>Two spaces, never tabs. A list item is <code>- </code>, and everything belonging to it lines up under its first key. Quote
any string with a <code>:</code> or a <code>#</code> in it. The banner above doesn&rsquo;t strictly need its quotes, but quoting text
you&rsquo;ll show humans is a good habit. VS Code&rsquo;s YAML extension (in the lab) underlines most mistakes before
Ansible sees them.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/ansible-101/#chapter-2">Chapter 2 of the lab</a> builds this playbook on all three switches, proves the
second run changes nothing, then previews a domain name and LLDP with check mode before applying them.</p>
<p>Next, in <a href="/lessons/ansible-101/variables-and-facts/">lesson 3</a>, we stop hard-coding values in playbooks: variables
per group and per host, which one wins, and asking the switches for facts we can use.</p>
]]></content:encoded></item><item><title>Ansible Inventory and Ad-Hoc Commands for Network Switches (Ansible 101 for Networking, Lesson 1)</title><link>https://networkdoodles.com/lessons/ansible-101/hello-ansible/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/ansible-101/hello-ansible/</guid><category>ansible</category><category>network-automation</category><category>automation</category><category>capeos</category><category>containerlab</category><category>howto</category><description>What Ansible does when the target is a switch: build an inventory for a Nokia SR Linux fabric and query every switch with one ad-hoc command. Includes a lab.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Most Ansible tutorials lose network engineers in the first five minutes. They install nginx on three Ubuntu
servers, talk about SSH keys and <code>become: true</code>, and somewhere around &ldquo;now let&rsquo;s template an Apache vhost&rdquo; you
close the tab, because none of that is your job.</p>
<p>This course is the one I wish I&rsquo;d had. Every example is a switch. Every lab task runs against a real
leaf-spine fabric. By the end of eight lessons you&rsquo;ll have roles, a vaulted password, an execution environment
and a pipeline, and you&rsquo;ll know <em>why</em> each of them exists, not just which YAML to paste.</p>
<p>Lesson 1 is the foundation: what Ansible actually does when the thing on the other end is a network device,
how an inventory works, and how to ask three switches a question with a single command.</p>
<hr>
<h2 id="what-ansible-is-for-us">What Ansible is (for us)</h2>
<p>Ansible is a tool that makes things match a description. You describe what should be true (&ldquo;this switch has
this banner, these NTP servers, these ports&rdquo;), Ansible connects to the device, compares, and changes only
what&rsquo;s different. Run it again and nothing happens, because everything already matches. That property has a
name, <strong>idempotency</strong>, and it&rsquo;s the whole reason Ansible beats a folder of scripts.</p>
<p>Three things to know up front:</p>
<ol>
<li><strong>It&rsquo;s agentless.</strong> Nothing gets installed on the switch. Ansible connects in over SSH or an API, does its
work, and leaves.</li>
<li><strong>It&rsquo;s push.</strong> You (or a pipeline) run it. The devices don&rsquo;t phone home on a schedule.</li>
<li><strong>For network devices, the code runs on your machine, not on the device.</strong> This is the one that trips up
people coming from server tutorials. On a Linux server, Ansible copies a small Python program over and runs
it there. A switch can&rsquo;t run arbitrary Python, so network modules run <em>locally</em> on the control node and
talk to the device through a <strong>connection plugin</strong>.</li>
</ol>
<p>That third point is why network Ansible looks a little different from server Ansible:</p>
<table>
  <thead>
      <tr>
          <th></th>
          <th>Servers</th>
          <th>Network devices</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Where the module runs</td>
          <td>On the server</td>
          <td>On your machine (the control node)</td>
      </tr>
      <tr>
          <td>How Ansible connects</td>
          <td><code>ssh</code></td>
          <td><code>network_cli</code> (SSH + CLI), <code>httpapi</code> (REST/JSON-RPC), <code>netconf</code></td>
      </tr>
      <tr>
          <td><code>gather_facts</code></td>
          <td>Useful</td>
          <td>Usually off: there&rsquo;s no Python on the far end to gather them</td>
      </tr>
      <tr>
          <td><code>become</code></td>
          <td>sudo</td>
          <td>Enable mode, on platforms that have one</td>
      </tr>
  </tbody>
</table>
<p>Once you know which connection plugin your platform uses, the rest of Ansible is the same everywhere.</p>
<hr>
<h2 id="the-lab-three-switches-you-dont-have-to-buy">The lab: three switches you don&rsquo;t have to buy</h2>
<p>Every lesson in this course has a <a href="/labs/ansible-101/">lab chapter</a>. The lab is a small leaf-spine fabric of
three switches running in containerlab, with a Linux host on each leaf:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">             ┌──────────┐
</span></span><span class="line"><span class="cl">             │  spine1  │
</span></span><span class="line"><span class="cl">             └─┬──────┬─┘
</span></span><span class="line"><span class="cl">           Gi1 │      │ Gi2
</span></span><span class="line"><span class="cl">           Gi1 │      │ Gi1
</span></span><span class="line"><span class="cl">       ┌───────┴┐    ┌┴───────┐
</span></span><span class="line"><span class="cl">       │ leaf1  │    │ leaf2  │
</span></span><span class="line"><span class="cl">       └───┬────┘    └────┬───┘
</span></span><span class="line"><span class="cl">        Gi2│              │Gi2
</span></span><span class="line"><span class="cl">         host1          host2
</span></span></code></pre></div><p>The switches run <strong>CapeOS Bolt</strong>, a network OS built for labs, with the command line most network engineers
learned first: <code>show running-config</code>, <code>configure terminal</code>, <code>interface GigabitEthernet1</code>, <code>write memory</code>. I
wanted that on purpose for a first Ansible course. Every config line in a playbook is a line you&rsquo;d type
yourself, and anything Ansible does, you can check by logging in and looking.</p>
<p>None of the ideas here are tied to one vendor. The modules change from platform to platform; inventories,
playbooks, variables, roles and vaults don&rsquo;t.</p>
<hr>
<h2 id="meet-ansible">Meet Ansible</h2>
<p>When you install Ansible you get two kinds of thing, and it helps to keep them apart.</p>
<p><strong>ansible-core</strong> is the engine: the <code>ansible</code> and <code>ansible-playbook</code> commands, the playbook language, and a
small set of built-in modules (<code>debug</code>, <code>copy</code>, <code>template</code>, <code>set_fact</code>). It knows nothing about switches.</p>
<p><strong>Collections</strong> are the drivers: packages of modules and plugins for a platform, usually written by the
vendor or the community, installed and versioned separately from the engine. The lab&rsquo;s switches speak the
classic IOS-style CLI, so the lab uses the <strong><code>cisco.ios</code></strong> collection, plus <code>ansible.netcommon</code>, which holds
the connection plugins that every network collection builds on.</p>
<p>Every module has a fully qualified name that says which driver you&rsquo;re calling: <code>cisco.ios.ios_command</code>,
<code>cisco.ios.ios_config</code>, <code>ansible.builtin.debug</code>. You&rsquo;ll meet collections properly in lesson 6.</p>
<p><code>ansible --version</code> tells you both what engine you have and which settings it found:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">ansible [core 2.20.1]
</span></span><span class="line"><span class="cl">  config file = /workspaces/ansible-101/ansible.cfg
</span></span><span class="line"><span class="cl">  ...
</span></span></code></pre></div><p>That <strong><code>config file</code></strong> line is the one to look at. Ansible reads its settings from an <code>ansible.cfg</code> file,
and the first one it finds wins: the <code>ANSIBLE_CONFIG</code> environment variable, then <code>ansible.cfg</code> in the current
folder, then <code>~/.ansible.cfg</code> in your home folder, then <code>/etc/ansible/ansible.cfg</code>. The project&rsquo;s file is where
the inventory path, the output format and, later, the vault settings live. If that line says <code>None</code>, Ansible
isn&rsquo;t using any of it, and everything else in this post will mysteriously fail. More on that below.</p>
<hr>
<h2 id="the-inventory-who-ansible-talks-to">The inventory: who Ansible talks to</h2>
<p>Ansible needs a list of devices. That list is the <strong>inventory</strong>, and it&rsquo;s just a file. The lab&rsquo;s is YAML:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nt">all</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">children</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">fabric</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">children</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">spines</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">hosts</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">spine1</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">leaves</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span><span class="nt">hosts</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">leaf1</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="nt">leaf2</span><span class="p">:</span><span class="w">
</span></span></span></code></pre></div><p>Read it top down:</p>
<ul>
<li><strong><code>all</code></strong> is a group Ansible creates for you. Everything is in it.</li>
<li><strong><code>fabric</code></strong> is a group of groups (<code>children</code>). It holds the <code>spines</code> and the <code>leaves</code>.</li>
<li><strong><code>spines</code></strong> and <strong><code>leaves</code></strong> hold the actual hosts.</li>
</ul>
<p>Groups are the most underrated feature in Ansible. They&rsquo;re how you say &ldquo;every leaf&rdquo; or &ldquo;every switch at the
Charlotte site&rdquo; or &ldquo;every device that&rsquo;s managed by the pipeline&rdquo; without listing hostnames. A host can be in as
many groups as you like. Design them around how you <em>talk</em> about the network: by role, by site, by platform.</p>
<p><code>ansible-inventory --graph</code> reads the file back the way Ansible understands it:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">@all:
</span></span><span class="line"><span class="cl">  |--@ungrouped:
</span></span><span class="line"><span class="cl">  |--@fabric:
</span></span><span class="line"><span class="cl">  |  |--@spines:
</span></span><span class="line"><span class="cl">  |  |  |--spine1
</span></span><span class="line"><span class="cl">  |  |--@leaves:
</span></span><span class="line"><span class="cl">  |  |  |--leaf1
</span></span><span class="line"><span class="cl">  |  |  |--leaf2
</span></span></code></pre></div><p>If that graph looks right, Ansible knows your network. It doesn&rsquo;t know how to <em>reach</em> it yet.</p>
<h3 id="telling-ansible-how-to-connect">Telling Ansible how to connect</h3>
<p>Every host needs a handful of <strong>connection variables</strong>. For the lab&rsquo;s switches they are:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="w">    </span><span class="nt">fabric</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">vars</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">ansible_connection</span><span class="p">:</span><span class="w"> </span><span class="l">ansible.netcommon.network_cli</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">ansible_network_os</span><span class="p">:</span><span class="w"> </span><span class="l">cisco.ios.ios</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">ansible_user</span><span class="p">:</span><span class="w"> </span><span class="l">admin</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">ansible_password</span><span class="p">:</span><span class="w"> </span><span class="l">capeos-lab</span><span class="w">
</span></span></span></code></pre></div><ul>
<li><strong><code>ansible_connection</code></strong> picks the connection plugin. <code>network_cli</code> means &ldquo;log in over SSH and type at the
CLI&rdquo;, the way you would. On an API-first platform this would be <code>httpapi</code> or <code>netconf</code> instead.</li>
<li><strong><code>ansible_network_os</code></strong> tells the plugin which CLI to expect, so it knows what the prompts and error
messages look like.</li>
<li><strong>User and password</strong> are in plain text, which should make you uncomfortable. Good. Lesson 7 fixes it.</li>
</ul>
<p>Putting them under <code>fabric: vars:</code> means every switch in the fabric gets them. In lesson 3 we&rsquo;ll move them out
of the inventory entirely, into <code>group_vars</code>, which is where they belong.</p>
<hr>
<h2 id="ad-hoc-commands-one-module-many-switches-no-playbook">Ad-hoc commands: one module, many switches, no playbook</h2>
<p>You don&rsquo;t need a playbook to use Ansible. An <strong>ad-hoc command</strong> runs one module against a group of hosts,
right from the shell:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">ansible fabric -m cisco.ios.ios_command -a <span class="s2">&#34;commands=&#39;show version&#39;&#34;</span>
</span></span></code></pre></div><p>That&rsquo;s: <em>against the <code>fabric</code> group, run the module <code>cisco.ios.ios_command</code>, with these arguments.</em> Ansible
logs in to all three switches at once, types <code>show version</code>, and prints what each one says (as YAML, because
the lab&rsquo;s <code>ansible.cfg</code> asks for readable output instead of a wall of JSON):</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">leaf1 | SUCCESS =&gt;
</span></span><span class="line"><span class="cl">    changed: false
</span></span><span class="line"><span class="cl">    stdout:
</span></span><span class="line"><span class="cl">    - |-
</span></span><span class="line"><span class="cl">        CapeOS Software (CO-BOLT), Version 0.1.2, LAB USE ONLY
</span></span><span class="line"><span class="cl">        ...
</span></span><span class="line"><span class="cl">        Processor board ID CAPEQ3I7EKD
</span></span><span class="line"><span class="cl">        ...
</span></span></code></pre></div><p>A few things worth noticing:</p>

<figure class="netsim" data-netsim tabindex="0" aria-label="One ad-hoc command against the fabric group: the inventory names three switches, the module runs on the control node, opens SSH to all three at once, types show version and brings back each answer, then patterns narrow it to fewer switches. Use the buttons, or the left and right arrow keys, to step through it." data-autoplay="false">
  <svg class="ns-svg" role="img" aria-label="One ad-hoc command against the fabric group: the inventory names three switches, the module runs on the control node, opens SSH to all three at once, types show version and brings back each answer, then patterns narrow it to fewer switches"></svg>
  <div class="ns-ctl">
    <button class="icon-btn" type="button" data-ns="restart" aria-label="Back to the first step" title="Start again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="prev" aria-label="Previous step" title="Previous step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
</button>
    <button class="btn sm primary ns-play" type="button" data-ns="play" aria-pressed="false"><span data-ns-play>Play</span></button>
    <button class="icon-btn" type="button" data-ns="next" aria-label="Next step" title="Next step"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
</button>
    <button class="icon-btn" type="button" data-ns="again" aria-label="Play this step again" title="Play this step again"><svg class="ico" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v4h4"/></svg>
</button>
    <span class="ns-count mono" data-ns-count></span>
    <button class="btn sm ns-speed" type="button" data-ns="speed" aria-pressed="false">Slow: off</button>
  </div>
  <div class="ns-dots" data-ns-dots role="group" aria-label="Jump to a step"></div>
  <figcaption class="ns-caption" data-ns-caption aria-live="polite"></figcaption>
  <div class="ns-panels">
    <div class="ns-codebox" data-ns-code hidden></div>
    <div class="ns-frame" data-ns-frame hidden></div>
    <div class="ns-tablebox" data-ns-table hidden></div>
  </div>
  <script type="application/json">{"h":340,"links":[["inv","ctl"],["ctl","spine1"],["ctl","leaf1"],["ctl","leaf2"]],"narrow":{"at":{"ctl":[270,70],"inv":[80,70],"leaf1":[180,290],"leaf2":[300,290],"spine1":[60,290]},"h":380,"w":360},"nodes":{"ctl":{"kind":"laptop","label":"Control node","sub":"runs the module","x":310,"y":160},"inv":{"kind":"file","label":"hosts.yml","sub":"the inventory","x":90,"y":160},"leaf1":{"kind":"switch","label":"leaf1","sub":"leaves","x":620,"y":170},"leaf2":{"kind":"switch","label":"leaf2","sub":"leaves","x":620,"y":275},"spine1":{"kind":"switch","label":"spine1","sub":"spines","x":620,"y":65}},"steps":[{"code":{"hl":[0],"lines":["ansible fabric -m cisco.ios.ios_command -a \"commands='show version'\""],"title":"ad-hoc command"},"hot":["inv","spine1","leaf1","leaf2"],"table":{"cols":["host","group","result"],"rows":[["spine1","spines",""],["leaf1","leaves",""],["leaf2","leaves",""]],"title":"ansible fabric -m cisco.ios.ios_command"},"text":"`fabric` holds the `spines` group (spine1) and the `leaves` group (leaf1, leaf2). One name, three switches.","title":"The inventory says who."},{"hot":["ctl"],"links":[["inv","ctl"]],"say":{"ctl":"ios_command\nruns here"},"text":"A switch can't run Python. `ios_command` runs on the control node and drives each switch through the `network_cli` plugin.","title":"The module runs here, not on the switch."},{"hot":["ctl"],"links":[["ctl","spine1"],["ctl","leaf1"],["ctl","leaf2"]],"packets":[{"label":"show version","path":["ctl","spine1"]},{"label":"show version","path":["ctl","leaf1"]},{"label":"show version","path":["ctl","leaf2"]}],"text":"`network_cli` logs in to each switch as `admin` and types at the CLI, the way you would: `show version`.","title":"SSH to all three at once."},{"good":["spine1","leaf1","leaf2"],"packets":[{"c":"green","label":"stdout","path":["spine1","ctl"]},{"c":"green","label":"stdout","path":["leaf1","ctl"]},{"c":"green","label":"stdout","path":["leaf2","ctl"]}],"set":{"leaf1":"CapeOS 0.1.2","leaf2":"CapeOS 0.1.2","spine1":"CapeOS 0.1.2"},"table":{"cols":["host","group","result"],"rows":[["spine1","spines","SUCCESS, changed: false"],["leaf1","leaves","SUCCESS, changed: false"],["leaf2","leaves","SUCCESS, changed: false"]],"title":"ansible fabric -m cisco.ios.ios_command"},"text":"Each one comes back `SUCCESS` with `changed: false`. `show` commands don't change anything.","title":"Every switch answers."},{"code":{"hl":[0],"lines":["ansible fabric:!spines -m cisco.ios.ios_command -a \"commands='show version'\""],"title":"ad-hoc command"},"dim":["spine1"],"hot":["leaf1","leaf2"],"links":[["ctl","leaf1"],["ctl","leaf2"]],"packets":[{"label":"show version","path":["ctl","leaf1"]},{"label":"show version","path":["ctl","leaf2"]}],"table":{"cols":["host","group","result"],"rows":[["spine1","spines","not asked"],["leaf1","leaves","SUCCESS, changed: false"],["leaf2","leaves","SUCCESS, changed: false"]],"title":"ansible fabric -m cisco.ios.ios_command"},"text":"`fabric:!spines` means every switch in the fabric except the spines. Same syntax in playbooks.","title":"Patterns pick the hosts."},{"code":{"hl":[0],"lines":["ansible leaf1 -m cisco.ios.ios_command -a \"commands='show version | include board'\""],"title":"ad-hoc command"},"dim":["spine1","leaf2"],"hot":["leaf1"],"links":[["ctl","leaf1"]],"packets":[{"label":"include board","path":["ctl","leaf1"]},{"at":1,"c":"green","label":"1 line","path":["leaf1","ctl"]}],"say":{"leaf1":"Processor board ID\nCAPEQ3I7EKD"},"sayAt":{"leaf1":{"narrow":"above","wide":"left"}},"table":{"cols":["host","group","result"],"rows":[["spine1","spines","not asked"],["leaf1","leaves","SUCCESS, changed: false"],["leaf2","leaves","not asked"]],"title":"ansible fabric -m cisco.ios.ios_command"},"text":"`leaf1` alone, with `| include board`. The CLI filters the output, so one line comes back instead of a page.","title":"One switch, filtered on the switch."}],"w":760}</script>
</figure>
<script src="/js/netsim.c40a98d103487ae5866edfa12abb4afc1d3aa7ad2d12fed4fe925fe00b588106.js" integrity="sha256-xAqY0QNIeuWGbt&#43;hKrtK/B06p60tEv7U/pJf4AtYgQY=" defer></script>

<ul>
<li><strong>The pattern is flexible.</strong> <code>fabric</code>, <code>leaves</code>, <code>leaf1</code>, <code>leaf*</code>, <code>fabric:!spines</code> (every switch except
the spines). Same syntax you&rsquo;ll use in playbooks.</li>
<li><strong>Quoting is where ad-hoc commands bite.</strong> Arguments are <code>key=value</code>, and a show command has spaces in it,
so it goes in single quotes inside the double-quoted argument string. Anything with a list or nested data
breaks the <code>key=value</code> format in confusing ways. I lost twenty minutes to this building the lab. When in
doubt, pass JSON in single quotes.</li>
<li><strong>The CLI&rsquo;s own tools still work.</strong> <code>show version | include board</code> filters on the switch, exactly as it
would if you were logged in, and brings back one line instead of a page.</li>
<li><strong>It&rsquo;s read-only, because the commands are.</strong> <code>ios_command</code> types what you give it, and <code>show</code> commands
don&rsquo;t change anything. Ad-hoc commands <em>can</em> change things, which is exactly why I use them almost only for
questions: &ldquo;which version is everything running?&rdquo;, &ldquo;who has an interface down?&rdquo;, &ldquo;what&rsquo;s the serial number
of leaf1?&rdquo;</li>
</ul>
<hr>
<h2 id="where-people-get-it-wrong">Where people get it wrong</h2>
<h3 id="1-ansible-quietly-ignoring-your-config-file">1. Ansible quietly ignoring your config file</h3>
<p>Remember the <code>config file =</code> line? Ansible reads <code>ansible.cfg</code> from the folder you run it in, <strong>unless that
folder is world-writable</strong>, in which case it refuses, because anyone could have planted that file. It prints
one warning and carries on with defaults: no inventory, nothing works, and the error you see is &ldquo;no hosts
matched&rdquo;.</p>
<p>I hit this building the lab: Codespaces checks repos out into a world-writable folder. The fix is to name the
file explicitly with the <code>ANSIBLE_CONFIG</code> environment variable, which the lab&rsquo;s dev container does for you.
If <code>ansible --version</code> ever says <code>config file = None</code>, that&rsquo;s your problem.</p>
<h3 id="2-reaching-for-ping">2. Reaching for <code>ping</code></h3>
<p>Every server tutorial starts with <code>ansible all -m ping</code>. On network devices it&rsquo;s misleading: the <code>ping</code> module
needs Python on the far end, which a switch doesn&rsquo;t have. Use a read-only module from your platform&rsquo;s collection
instead, like a <code>show</code> command through <code>ios_command</code>. If it answers, you&rsquo;re connected.</p>
<h3 id="3-leaving-gather_facts-on">3. Leaving <code>gather_facts</code> on</h3>
<p>Playbooks gather facts by default, which on a network device means a slow failure or a pile of warnings. Every
network play should start with <code>gather_facts: false</code> unless you know you need facts, and then you gather them
with the platform&rsquo;s own module (<code>cisco.ios.ios_facts</code>, in lesson 3). You&rsquo;ll see this in every playbook in the
course.</p>
<h3 id="4-one-giant-all-group">4. One giant <code>all</code> group</h3>
<p>An inventory with forty hostnames and no groups works today and hurts forever. You can&rsquo;t say &ldquo;the leaves&rdquo; or
&ldquo;Charlotte&rdquo;, so every playbook ends up with a hand-maintained host list. Groups cost nothing. Add them before
you need them.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/ansible-101/#chapter-1">Chapter 1 of the lab</a> opens the fabric in your browser, has you write this
inventory, and asks the switches for their versions and leaf1&rsquo;s serial number with ad-hoc commands.</p>
<p>Next time, in <a href="/lessons/ansible-101/first-playbook/">lesson 2</a>, we write a real playbook, change all three
switches at once, and prove that running it twice changes nothing.</p>
]]></content:encoded></item></channel></rss>