Ansible –extra-vars

Note that this post uses NTC-Ansible. Installation instructions can be found here.

Often you will see variables defined in a Playbook, a Task and/or a variables file such as group_vars or host_vars, as shown below:

A full list of variable locations and their order of precedence can be found here.

What if you don’t want to use statically configured variables? For example, maybe you need to run various show  commands and don’t want to have to write a task for each. This is there --extra-vars  comes into great use.

Using this hosts file:

And this Playbook:

Gives us complete flexibility. Using it in conjunction with --extra-vars  allows us to specify:

  • The host or group we’d like to run the command on.
  • The ability to specify the credentials when running the command (as opposed to storing them in a variables file).
  • The platform (IOS, NXOS, etc).
  • Whether we’d like to use Telnet or SSH.
  • Which command we’d like to run.

It would be near impossible to replicate this functionality through the use of individual, static Tasks.

We can use this command to run the Playbook on the ‘gns3’ group:

Doing so produces the following output:

 

Excellent, it works! However, sending only one command isn’t going to be all that useful. With a couple of minor changes to our code, we can now send multiple commands at once:

To take advantage of our modifications, we simply need to send our commands in a list  as opposed to a string :

For more information on lists, see the Lists & Dicts page.

Let’s take a look when we run this command:

WOW, look at the size of that output! Is that a mistake? No, it’s not. This is done intentionally and is a result of the loop being added to the Playbook. (See the Cleaning Up Ansible Loop Outputs post for information on how to clean this up.)

If we sift through the output we can see that our Playbook did in fact work as desired, as per the sections below:

Git

This playbook is available here in my Github repo.

Knowledge Base

See the Ansible section of my Knowledge Base for more information.

As always, if you have any questions or have a topic that you would like me to discuss, please feel free to post a comment at the bottom of this blog entry, e-mail at will@oznetnerd.com, or drop me a message on Twitter (@OzNetNerd).

Note: This website is my personal blog. The opinions expressed in this blog are my own and not those of my employer.

Leave a Reply

Your email address will not be published. Required fields are marked *