Network Automation with Ansible

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is the primary focus of the course 'Automating Networks with Ansible the Right Way'?

  • Fundamentals of Python programming for network engineers.
  • System administration tasks using Ansible on Linux-based systems.
  • Advanced MPLS configurations and troubleshooting.
  • Designing, implementing, operating, and troubleshooting automation solutions in a complex network using Ansible. (correct)

Which of the following is a key difference when using Ansible for network automation compared to system administration?

  • System administration relies heavily on SSH transport, while network automation requires additional connectivity methods.
  • Network automation often involves devices without native Python support, requiring module logic to run on the control machine. (correct)
  • Ansible is primarily designed for system administration, making it less effective for network automation.
  • Network devices always have Python installed locally, simplifying module execution.

In the context of the Globomantics network scenario, what is the main purpose of MPLS VPNs?

  • To provide internet access to all Globomantics customers.
  • To simplify BGP route exchanges between Globomantics and its customers.
  • To eliminate the need for route targets in network configurations.
  • To enable multitenancy by keeping customer data separate across geographically dispersed sites. (correct)

How do route targets (RTs) contribute to multitenancy in an MPLS network?

<p>They act as numeric tags applied to BGP routes to determine VPN membership and isolation. (B)</p> Signup and view all the answers

Which Ansible component is used to define global runtime settings, such as the location of the inventory file and log storage?

<p>The Ansible configuration file. (A)</p> Signup and view all the answers

What is the purpose of the Ansible inventory file?

<p>To enumerate all of the hosts and groups of hosts being managed by Ansible. (D)</p> Signup and view all the answers

In Ansible, what is a 'playbook'?

<p>A file containing a list of plays, which define automation tasks. (C)</p> Signup and view all the answers

Within an Ansible playbook, what is the purpose of a 'task'?

<p>To perform a specific action on a managed host, typically using a module. (C)</p> Signup and view all the answers

Which variable is used to inform Ansible's SSH logic about the type of network device it is connecting to?

<p>ansible_network_os (B)</p> Signup and view all the answers

What file format is commonly used for Ansible variable files?

<p>YAML (B)</p> Signup and view all the answers

Why is disabling fact gathering a common practice in network-oriented Ansible playbooks?

<p>Networking modules typically run on the control machine, making fact gathering on target routers unnecessary. (C)</p> Signup and view all the answers

What is the benefit of using a playbook-level configuration file instead of the global Ansible configuration file?

<p>It improves portability and version control by keeping configurations contained within the project code. (A)</p> Signup and view all the answers

What is the primary purpose of 'retry files' in Ansible?

<p>To list failed hosts for re-running tasks specifically on those hosts. (C)</p> Signup and view all the answers

In Ansible, what is the purpose of the group_vars folder?

<p>To store variables that are automatically inherited by hosts within a specific group. (D)</p> Signup and view all the answers

What is the function of the register keyword in an Ansible task?

<p>To store the result of a task execution in a variable for later use. (A)</p> Signup and view all the answers

What is the purpose of the debug module in Ansible?

<p>To print information, such as variable values, to the console during playbook execution. (A)</p> Signup and view all the answers

In Ansible, what is the purpose of a 'handler'?

<p>To execute tasks conditionally, only when notified by another task. (B)</p> Signup and view all the answers

What does it mean for an operation to be 'idempotent' in the context of Infrastructure as Code?

<p>The operation only makes changes when necessary, avoiding unnecessary modifications on subsequent runs. (A)</p> Signup and view all the answers

What is the primary goal of Infrastructure as Code (IaC)?

<p>To automate and manage infrastructure using code and declarative configuration files. (C)</p> Signup and view all the answers

What is the purpose of 'version control' in an IaC environment?

<p>To track and manage changes to infrastructure code, allowing for rollback and collaboration. (A)</p> Signup and view all the answers

What benefit does Infrastructure as Code provide in multi-vendor network environments?

<p>It provides a common framework for interfacing with different devices, abstracting away vendor-specific command differences. (A)</p> Signup and view all the answers

What is Continuous Integration and Continuous Deployment (CI/CD) in the context of IaC?

<p>An automated process for testing and deploying infrastructure changes to production. (D)</p> Signup and view all the answers

What is a significant business benefit of adopting Infrastructure as Code?

<p>Improved quality by reducing variability and allowing for more time for cognitive tasks. (A)</p> Signup and view all the answers

What is the purpose of the host_vars directory in Ansible?

<p>To store variables specific to individual hosts. (B)</p> Signup and view all the answers

What is Jinja2 primarily used for in Ansible?

<p>To create configuration templates using loops, conditional logic, and variable substitution. (A)</p> Signup and view all the answers

What is the purpose of the notify keyword in an Ansible task?

<p>To call a handler, which is conditionally executed based on events. (B)</p> Signup and view all the answers

When using the ios_config module, what does the save_when: changed option accomplish?

<p>It saves the running configuration to the startup configuration only if changes were made during the task. (D)</p> Signup and view all the answers

What is the benefit of using the cli_config module in Ansible?

<p>It is platform-agnostic and can handle any network CLI by relying on the Ansible network OS field. (A)</p> Signup and view all the answers

When is it most appropriate to use feature-specific Ansible modules (e.g., ios_vrf) instead of generic configuration management modules (e.g., ios_config)?

<p>When needing fewer moving parts and a less complex design for a specific task. (D)</p> Signup and view all the answers

Why can removing stale configurations be challenging when using CLI-based Infrastructure as Code solutions?

<p>Ansible does not want to make assumptions about what to remove, as this could be dangerous. (D)</p> Signup and view all the answers

What is the primary purpose of custom filters in Ansible?

<p>To extend Ansible's functionality with custom Python code for data manipulation. (A)</p> Signup and view all the answers

Why is it beneficial to use custom filters for complex data manipulations in Ansible?

<p>Custom filters simplify playbook syntax and reduce overall complexity by leveraging Python's flexibility. (D)</p> Signup and view all the answers

What does the filters function in a custom Ansible filter module return?

<p>A dictionary mapping Ansible filter names to Python function names. (B)</p> Signup and view all the answers

What is the purpose of regular expressions (regex) in the context of network automation?

<p>To match input strings against generic patterns and extract specific data fields. (D)</p> Signup and view all the answers

What is the primary goal of unit testing custom filters in Ansible?

<p>To pass static data to individual code segments and assert the results, preventing regressions. (B)</p> Signup and view all the answers

What is the benefit of using Ansible itself for unit testing custom filters?

<p>It's simpler and validates real-life applications of the filter without abstract test suites. (A)</p> Signup and view all the answers

In mathematical set theory, what does the 'set difference' operation (A - B) determine?

<p>Elements that exist in set A but not in set B. (B)</p> Signup and view all the answers

How can set difference be used to solve the problem of unwanted configurations?

<p>It can be used to surgically determine which configurations need to be removed. (A)</p> Signup and view all the answers

When using the rt_diff filter, which list isn't looped over?

<p>The running config VRF dictionary keys in the filter. (D)</p> Signup and view all the answers

What is the key benefit of using Ansible roles?

<p>They enable encapsulation of Ansible components into self-contained, reusable packages. (B)</p> Signup and view all the answers

What is Ansible Galaxy?

<p>A website with version control, and code repository where roles can be uploaded and shared within the Ansible community. (C)</p> Signup and view all the answers

Which of the following best describes the role of Pluralsight's course 'Automating Networks with Ansible the Right Way'?

<p>Detailing the automation of intricate network solutions using Ansible. (B)</p> Signup and view all the answers

What is a key recommendation for maximizing the learning experience in the 'Automating Networks with Ansible the Right Way' course?

<p>Basic Python coding skills and networking knowledge. (B)</p> Signup and view all the answers

Regarding Ansible's applicability in network automation compared to other IT systems, what is a primary consideration?

<p>Network devices often lack native Python support, affecting module execution. (A)</p> Signup and view all the answers

In the context of network automation using Ansible, what is the significance of understanding various connectivity methods beyond SSH?

<p>Network devices offer a wide array of connectivity methods, influencing automation strategies. (B)</p> Signup and view all the answers

What is the key architectural benefit of MPLS VPNs in the Globomantics network scenario?

<p>Providing multitenancy and segregation of customer data. (B)</p> Signup and view all the answers

How do route targets (RTs) enable customized connectivity in an MPLS network?

<p>By selectively importing or exporting routes to define VPN membership and topology. (D)</p> Signup and view all the answers

What is the role of routers R1 and R2 in the Globomantics MPLS network automation project?

<p>Connecting directly to customer sites and enforcing route target policies. (D)</p> Signup and view all the answers

How does Ansible's configuration file relate to playbook execution?

<p>It defines global runtime settings that affect the entire playbook, but can be overridden. (A)</p> Signup and view all the answers

Within the Ansible framework, how are individual group and host variables utilized during playbook execution?

<p>They are consumed primarily at the task level to parameterize module behavior. (D)</p> Signup and view all the answers

When configuring Ansible to connect to network devices, what is the purpose of the ansible_network_os variable?

<p>To instruct Ansible's SSH logic about the type of network device. (C)</p> Signup and view all the answers

Why is it preferable to use a playbook-level configuration file over the global Ansible configuration file in network automation projects?

<p>Playbook-level configurations improve portability and version control of project settings. (C)</p> Signup and view all the answers

How is a Python virtual environment beneficial in the context of Ansible network automation?

<p>It isolates project dependencies, ensuring consistent Ansible and Python versions. (A)</p> Signup and view all the answers

What is the purpose of using the ios_command module in Ansible for network automation?

<p>To run <code>exec</code> level commands on Cisco IOS devices and retrieve their output. (D)</p> Signup and view all the answers

What approach should be used to extract the standard output from the structured data when using the ios_command module?

<p>Reference the <code>stdout</code> key with appropriate list indexing in the registered variable. (C)</p> Signup and view all the answers

What is the function of the run_once task-level directive in Ansible?

<p>It executes a task only one time, regardless of the number of hosts in the play. (D)</p> Signup and view all the answers

What is the purpose of Infrastructure as Code (IaC)?

<p>Managing and provisioning infrastructure through code, rather than manual processes. (B)</p> Signup and view all the answers

Which of the following is a core component of Infrastructure as Code?

<p>Declaring the desired state of the infrastructure. (D)</p> Signup and view all the answers

Why is the concept of 'idempotence' crucial in Infrastructure as Code (IaC)?

<p>It makes sure that an operation when executed multiple times only makes changes when necessary. (C)</p> Signup and view all the answers

How does Infrastructure as Code leverage abstraction in multivendor network environments?

<p>By providing per-platform templates and a common framework for interfacing with devices. (C)</p> Signup and view all the answers

How does version control enhance troubleshooting in an Infrastructure as Code environment?

<p>By providing a centralized repository of all changes with difference checking capabilities. (C)</p> Signup and view all the answers

What is the potential impact of Continuous Integration and Continuous Deployment (CI/CD) on network management in an IaC context?

<p>It automates the testing and deployment of network changes, making modifications routine. (B)</p> Signup and view all the answers

What is a key business benefit of adopting Infrastructure as Code?

<p>Achieving a faster, more stable network at a lower total cost. (D)</p> Signup and view all the answers

In Ansible, what is the purpose of the host_vars directory?

<p>To define variables specific to individual hosts. (A)</p> Signup and view all the answers

What is the primary function of Jinja2 templates in Ansible-based Infrastructure as Code?

<p>Transforming structured data into CLI commands using loops, conditional logic, and variable substitution. (A)</p> Signup and view all the answers

When using the ios_config module in Ansible, what is the function of the notify keyword?

<p>To trigger a handler conditionally based on task status. (A)</p> Signup and view all the answers

When deploying Infrastructure as Code to network devices, why can removing stale configurations be a challenge?

<p>Ansible avoids making assumptions about configuration removal to prevent unintended consequences. (D)</p> Signup and view all the answers

Why are custom filters useful in Ansible playbooks?

<p>They allow the execution of arbitrary Python code for complex data manipulations. (D)</p> Signup and view all the answers

In the context of Ansible, what is the primary role of the filters function within a custom filter module?

<p>To map Ansible filter names to Python function names. (C)</p> Signup and view all the answers

When writing custom filters in Ansible, why is it beneficial to keep advanced logic in Python and task orchestration in Ansible?

<p>It lowers the barrier for entry, allowing junior engineers to manage playbooks while advanced logic is handled by Python. (D)</p> Signup and view all the answers

What is the purpose of regular expressions (regex) in the context of network automation and custom filters?

<p>To match input strings against generic patterns and extract specific data fields. (A)</p> Signup and view all the answers

What is the main benefit of writing unit tests for custom filters in Ansible?

<p>To ensure that changes to the filter don't introduce regressions before running playbooks. (B)</p> Signup and view all the answers

Regarding the use of Ansible for unit testing custom filters, why is this approach effective?

<p>It's simple and validates the real-life application of the filter without an abstract test suite. (C)</p> Signup and view all the answers

How can set difference be used to solve the problem of unwanted configurations in network automation with Ansible?

<p>By surgically determining which configurations need to be removed from the network devices. (A)</p> Signup and view all the answers

What is the function of Ansible Galaxy?

<p>A repository for sharing and consuming Ansible roles within the community. (D)</p> Signup and view all the answers

In the 'Automating Networks with Ansible the Right Way' course, what prior knowledge is recommended for students to succeed?

<p>Basic Python coding skills and fundamental networking knowledge. (A)</p> Signup and view all the answers

How does Ansible's approach to network device management generally differ from its approach to Linux server management?

<p>Network devices often lack native Python support, requiring the control machine to execute modules. (C)</p> Signup and view all the answers

What role does Globomantics play in the context of the network automation scenarios presented in the course?

<p>A network service provider automating customer provisioning. (A)</p> Signup and view all the answers

In an MPLS VPN, what determines the level of connectivity and isolation between different customers?

<p>The configuration of route targets (RTs) associated with VPN routes. (D)</p> Signup and view all the answers

How does the Ansible configuration file influence playbook execution?

<p>It specifies global Ansible runtime settings, such as inventory location. (A)</p> Signup and view all the answers

How do playbooks utilize variables for specific hosts or groups?

<p>Playbooks use group and host variables at the task level. (A)</p> Signup and view all the answers

In Ansible network automation, what is the purpose of disabling fact gathering?

<p>To speed up playbook execution by avoiding unnecessary data collection. (B)</p> Signup and view all the answers

How do you configure a playbook to execute a particular task only once, regardless of the number of hosts?

<p>By using the <code>run_once: true</code> directive at the task level. (A)</p> Signup and view all the answers

Which of the following is a core principle behind Infrastructure as Code?

<p>Defining infrastructure as code for automated management. (B)</p> Signup and view all the answers

How does Infrastructure as Code (IaC) improve consistency and reduce errors in network management?

<p>By automating repetitive tasks and enforcing standardized configurations. (B)</p> Signup and view all the answers

In Ansible, what is the primary purpose of Jinja2 templates within the context of Infrastructure as Code?

<p>To transform structured data into device-specific configurations. (A)</p> Signup and view all the answers

What is a key challenge when applying Infrastructure as Code to network devices, particularly with CLI-based approaches?

<p>Removing stale configurations that are not part of the desired state. (A)</p> Signup and view all the answers

When writing custom filters in Ansible, why is it beneficial to delegate complex logic to Python?

<p>To simplify playbook design and improve readability. (B)</p> Signup and view all the answers

What is the primary purpose of using regular expressions (regex) when writing custom filters for network automation?

<p>To match patterns within text and extract specific data. (C)</p> Signup and view all the answers

Why should you write unit tests when creating custom filters in Ansible?

<p>To identify errors and regressions in filter logic. (B)</p> Signup and view all the answers

When using Ansible to unit test custom filters, what benefit is gained by using Ansible instead of a dedicated testing framework?

<p>It allows testing of the filter in a real-world application context. (C)</p> Signup and view all the answers

How can mathematical set difference be used to solve the problem of unwanted configurations on network devices?

<p>To determine which configurations exist but are not in the desired state. (A)</p> Signup and view all the answers

In the context of Ansible and Infrastructure as Code, what does 'abstraction' enable in multi-vendor network environments?

<p>A common framework for interfacing with different types of devices. (B)</p> Signup and view all the answers

In the context of Ansible, what is the main purpose of roles?

<p>To create reusable, self-contained packages of Ansible components. (B)</p> Signup and view all the answers

According to the course material, what is a significant business advantage of adopting Infrastructure as Code (IaC)?

<p>Faster delivery, improved quality, and lower operational costs. (D)</p> Signup and view all the answers

Flashcards

Ansible configuration file

A configuration file that defines global runtime settings for Ansible, such as the inventory file location and logging options.

Ansible inventory

A file that lists all the hosts and groups of hosts managed by Ansible.

Ansible variable files

Files that store group and host-specific data, often containing configuration settings.

Ansible playbooks

Files containing a list of plays that define the automation tasks to be executed by Ansible.

Signup and view all the flashcards

ansible_network_os

Specifies network device type for SSH.

Signup and view all the flashcards

ansible_user

The username Ansible uses to log in to the network device.

Signup and view all the flashcards

ansible_password

The password associated with the username used to log in to the network device.

Signup and view all the flashcards

group_vars folder

A way of automatically inheriting variables at the group level in Ansible.

Signup and view all the flashcards

ios_command module

A module for running exec-level commands on Cisco IOS devices.

Signup and view all the flashcards

copy module

A module for copying files to managed devices.

Signup and view all the flashcards

stdout

Describes the data structure of Ansible returns.

Signup and view all the flashcards

run_once

Ensures a task runs only once, even across multiple hosts.

Signup and view all the flashcards

inventory_hostname

A special variable that Ansible makes available, reflecting the hostname of each host.

Signup and view all the flashcards

IaC

Infrastructure as Code: Managing and provisioning infrastructure through code rather than manual processes.

Signup and view all the flashcards

host_vars

Directory for host-specific variables.

Signup and view all the flashcards

Jinja2

A text templating language used for generating configuration files dynamically.

Signup and view all the flashcards

save_when: changed

Instructs Ansible to copy the running-config to startup-config if any changes are required.

Signup and view all the flashcards

handler

A task that is conditionally executed only when notified by another task.

Signup and view all the flashcards

idempotent

An operation that can be executed multiple times without causing unintended side effects after the initial execution.

Signup and view all the flashcards

ios_config

A module used to apply configuration changes to network devices.

Signup and view all the flashcards

Abstraction

Uses a custom configuration template per device type.

Signup and view all the flashcards

cli_config

Module that intelligently handles any network CLI, using the Ansible network OS field.

Signup and view all the flashcards

lookup

Module to pass plaintext by using lookup to render the template manually.

Signup and view all the flashcards

ios_vrf

Module to manage VRF configurations on network devices without Jinja2 templates.

Signup and view all the flashcards

Custom Filter

A Python function that complements existing Ansible constructs, allowing for custom data manipulation within playbooks.

Signup and view all the flashcards

filter directory

Directory inside the plugins directory.

Signup and view all the flashcards

RE library

A Python library that provides a system to write regular expressions.

Signup and view all the flashcards

Unit test

Testing code segments.

Signup and view all the flashcards

Set

The mathematical term representing a collection of unique elements.

Signup and view all the flashcards

Set difference

Operation answering: which elements exist in one set, but not the other set?

Signup and view all the flashcards

Ansible Roles

Encapsulate components for reuse elsewhere.

Signup and view all the flashcards

ansible-galaxy

Shell command available when installing Ansible.

Signup and view all the flashcards

Ansible-galaxy Website

A website where roles can be uploaded and shared within the Ansible community.

Signup and view all the flashcards

Study Notes

  • This course focuses on automating networks with Ansible, emphasizing practical application and production-ready solutions.
  • The course covers designing, implementing, operating, and troubleshooting automation solutions in complex networks.
  • Key principles include Ansible-based network automation, infrastructure as code, design options (CLI and API-based), Python coding for Ansible customization, and bulletproofing playbooks.
  • Prior knowledge of Python, basic networking (CCNA level), and an introduction to Layer 3 VPNs are recommended.

Network Automation Differences

  • Ansible is typically used in systems administration, but involves some specific differences in network automation.
  • Most network devices lack native Python support, unlike Linux-based systems.
  • Ansible delegates module execution to managed devices with Python.
  • Without Python, the module logic runs on the Ansible control machine.
  • Network devices commonly use different connectivity methods beyond SSH.

MPLS Network Overview

  • Multiprotocol Label Switching (MPLS) enables multitenancy across geographically dispersed sites using VPNs.
  • Globomantics, a network service provider, automates customer provisioning using Ansible.
  • MPLS VPNs use Border Gateway Protocol (BGP) to exchange IP routes.
  • Route targets (RTs) are numeric tags applied to BGP routes, determining VPN membership.
  • Ansible primarily manages R1 and R2 routers.

Ansible Core Components

  • The Ansible configuration file defines global runtime settings like inventory file location and logging.
  • The Ansible inventory lists managed hosts and groups.
  • Variable files store group and host-specific data, significantly used for configuration settings.
  • Playbooks are the mainstay of Ansible, containing a list of plays.
  • Plays include tasks, which are specific actions to be accomplished on the target hosts.
  • The configuration file contains global operations while plays select groups from the inventory based on high level global operations that affect the entire playbook.
  • Group and host variables are consumed at the task level.
  • ansible_network_os specifies the type of network device.
  • ansible_user sets the login username.
  • ansible_password sets the login password.

Ansible Preparation Steps

  • Install Ansible and create a directory structure with basic component files.
  • Python virtual environment with Python version 3.6.7 and Ansible version 2.7.7 is used.
  • The default config file is in /etc/ansible/ansible.cfg, and playbook-level config files are recommended for portability.
  • Common defaults include disabling fact gathering (gathering: false), identifying the inventory file (inventory = inv.yml), and disabling retry files (retry_files_enabled = False).
  • The YAML inventory format is hierarchical, starting with the all group containing subgroups.
  • The group_vars folder automatically inherits variables at the group level.

First Ansible Playbook

  • A playbook lists plays, defining the play data and scope.
  • Tasks include names, modules, and options.
  • ios_command module runs exec-level commands on Cisco IOS devices.
  • The register task option stores the result.
  • The debug module prints output.
  • Ansible prints out the play and task names in the console log.

Playbook Logging Challenge

  • Output data should be represented as simple text, and configuration snippets backed up to files.
  • ansible-doc feature provides documentation of Ansible
  • Examine stdout, a list of strings, one per command issued.
  • JSON structure uses dot notation (e.g., cli_result.stdout) or Python notation (e.g., cli_result['stdout']).
  • The file module creates directories.
  • run_once accomplishes folder creation only once instead of N times.
  • The copy module writes content from memory to a file on the control machine.
  • inventory_hostname variable reflects the hostname of each host.

Infrastructure as Code (IaC)

  • Traditional network operators often manually determine the current state of devices and their configuration.
  • IaC allows operators to declare a desired state.
  • IaC solutions offer varying levels of abstraction for different environments.
  • Version control systems track changes made by all users with difference checking capabilities.

IaC Components

  • Idempotence means an operation can be executed multiple times without unnecessary changes after the initial setup.
  • Variables illustrate route target management using YAML data.
  • Ansible workflows can be designed generically with custom templates per device type.
  • Version control enables reverting to previous states, checking logs, and enhancing troubleshooting and postmortem processes.
  • Continuous Integration/Continuous Deployment (CI/CD) automates testing and deployment.

Business Benefits of IaC

  • Quality is improved by reducing variability.
  • Time is reallocated from mundane tasks to network design and planning.
  • Automation frameworks like Ansible are low or no cost.
  • Automation for a US Federal Government customer reduced defect rates, shortened lead times, and saved approximately $2 million annually.

Deploying "ios_config" for CLI-based IAC

  • The host_vars folder defines specific variables for individual hosts.
  • R1 and R2 have VRFs with route import and export lists.
  • Jinja2 templates allow loops for iteration and if/else statements for conditional logic.
  • The ios_config module makes changes to the router
  • The src option specifies the Jinja2 template file path.
  • The save_when: changed option copies the running-config to startup-config if changes are required.
  • The notify option calls a handler when changes occur.
  • Handlers listen for a specific signal (e.g., config_changed) and execute tasks conditionally
  • Handlers are used to print output only if there was a change.
  • Use ansible-doc to learn more about file and copy modules

Deploying "cli_config" for CLI-based IAC

  • Uses a more platform-agnostic approach with a mixed IOS and IOS XR network.
  • The inventory file includes additional hierarchy with ios_routers and iosxr_routers subgroups.
  • Subgroups allow defining OS-specific variables in the group_vars folder, such as ansible_network_os.
  • Templates are device-based (ios_vpn.j2 and iosxr_vpn.j2).
  • Module cli_config handles any network CLI via the ansible_network_os field.
  • set_fact module performs variable assignment.
  • The cli_config module uses lookup to render the template manually.
  • The handler is notified if a change occurs, and results are stored in cli_result.
  • A bug exists in cli_config: does not properly save IOS configurations.

Deploying "ios_vrf" for CLI-based IAC

  • Manages VPN membership configuration by just updating route targets in the network based on declarative statement without any templates.
  • The ios_vrf module passes a list of dictionaries.
  • Naming variables consistently with module suboptions helps stay organized.

Comparing CLI-based Infrastructure as Code Solutions

  • Generic solutions rely on modules like ios_config or cli_config.
  • Specific modules like ios_vrf have a limited set of features.
  • Generic solutions use Jinja2 templates, while specific solutions ingest structured data directly.

The Big Problem

  • Ansible may have difficulty removing stale configurations when using CLI-based Infrastructure as Code solutions.
  • Removing old configuration is challenging as Ansible does not want to make assumptions.
  • Basic IaC solutions are great at remediating missing route targets if any exist.

Custom Filters

  • Ansible is easily extendable using Python with custom filters, modules, and plugins.
  • Filters are Python functions that complement existing Ansible constructs.
  • Filters enable running arbitrary Python code in playbooks.
  • YAML-based DSL can be inflexible.
  • Python functions often reduce complexity
  • Ansible plugins need to be included in the config file.
  • The FilterModule class in Python is consumed by Ansible.
  • The filters function returns a dictionary mapping Ansible filter names to Python function names.

Simplest Possible Custom Filter

  • Filter extracts the BGP Autonomous System Number from the route target using Python.
  • Specify custom filters file path in the config file.
  • The FilterModule class creates a method called filters.
  • A statichmethod decorator is used since Ansible doesn’t need to instantiate this class.
  • Invoke custom filter using the pipe syntax.

Parser and Regex Basics

  • Python filter transforms the VRF definition text blob into a JSON structure.
  • Regular expressions (regex) match input strings against generic patterns for extracting data fields.
  • Named capture groups identify data.
  • Regex101.com support checking regex against sample text inputs.

Custom Parser for VRF Information Demo

  • The RE library is used for regular expressions.
  • A filter takes in a single string (text), which should be a delimited blob.
  • The big blob gets broken into smaller chunks, one per VRF.
  • A Python list comprehension combined with string splitting is used .
  • Iterate through each VRF stanza individually to search the VRF stanza for the VRF name, and store it in dictionary form.

Bullet-proofing Code with Unit Tests

  • Unit tests pass static data to individual code segments (custom filters).
  • Test the results by the use of static input.
  • Detect future changes to detect breaking changes without impacting production

Using Ansible for Filter Unit Testing

  • Use Ansible to test Ansible.
  • Playbook loads test cases defined in the task's directory.
  • One task file is created for each filter, and each task file contains individual test cases.
  • The play runs on localhost only and uses connection local.
  • The find module grabs YAML files that begin with test_ in the tasks directory.
  • The map filter grabs all path attributes from each dictionary and assembles them into a simple list of strings.
  • Walk the list of file names pulling each one into the playbook using the include_tasks directive.
  • The assert module asserts provided list of conditions are all true.

Set Theory Basics

  • A set is a mathematical term representing a collection of unique elements.
  • Sets are unsorted, unsorted collections of unique elements.
  • Operations include union, intersection, and difference.
  • Set difference answers the set difference: which one is in one set, but is NOT in the other set.

Set Operations in Python

  • want represents the desired state (YAML lists).
  • have represents the current route target configuration.
  • want - have identifies route targets to add (present in desired state, not in current state).
  • have - want identifies route targets to remove (currently configured, not in desired state).

Custom Filter for Route-targeting Presence Determination

  • Filter takes two arguments: list of VRFs from intended state and dictionary of VRFs from running configuration.
  • Function returns a list of VRFs.
  • Uses get function that works with a list indexes, returns NOne if matching value found,.
  • Adds or deletes based on matching filter conditions
  • Set intersection not required because its a non change

Unit Tests For the Custom Filter

  • Use static data to mock up YAML-formatted data.
  • Mock variables such as run-vrf-dict to compare current stated vs intended state
  • Assert individual data fields are correct.

Fitting the Pieces Together

  • The desired state is stored in per-host variable files using YAML format.
  • The playbook captures the current VRF configuration.
  • Tasks: parse the lists of current import and export route targets; Compare to desired configurations and then Apply any route target additions or removals.
  • Jinja loops are nested for each set of commands
  • Commands loop to add the necessary data

The Whole Solution in Action

  • A Jinja2 template applies config changes.
  • Four inner loops add and delete route target import/export.
  • grep for seeing a high‑level view of a large Ansible playbook.
  • Steps: grab the VRF config, parse it, perform set difference, apply changes, and display changes if they occurred.
  • A key component is rt_diff filter
  • Use desired state route target lists via a script, run the playbook again, and the infrastructure updates appropriately; no more manual changes directly on devices.

Ansible Roles

  • An Ansible Role encapsulates Ansible components into a self-contained package for reuse.
  • Each Ansible Role will include unit tests for code
  • Roles are available via Ansbile Galaxy
  • Roles assist in scaling the Ansible architecture
  • Helps maximizes code reuse

Ansible Galaxy Refresher

  • ansible-galaxy is a shell command available to create or interfact with files from Ansible
  • Use ansible-galaxy list command to enumate installed Ansible Roles
  • Use ansible-galaxy search command to to search the Ansible-galaxy website
  • Use the ansible-galaxy install command to install the modules on to your Ansible distribution
  • Ansible's init command builds the directory

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

More Like This

Mastering Ansible Modules
20 questions

Mastering Ansible Modules

VisionarySugilite avatar
VisionarySugilite
Ansible Playbook Execution with Extra Variables
20 questions
Fortinet Modules for Ansible
20 questions
Ansible Fundamentals
6 questions

Ansible Fundamentals

NimbleCosecant avatar
NimbleCosecant
Use Quizgecko on...
Browser
Browser