Python

You are currently browsing the archive for the Python category.

Update: Ivan Pepelnjak reached out to me after this was published and suggested that it would make more sense to move the functions inside the defined class.  Doing this removes the functions from the global namespace and avoids the possibility of function names overlapping.  I think that’s a great idea so I’ve updated the examples below to align with this thinking.  Thanks Ivan!

I’ve been playing around with Ansible quite a bit lately.  One of the issues I’ve started to run into is that Ansible can’t always do what you want by default.  Put more plainly, Ansible can’t always easily do what you want.    Many times I found myself writing tasks to manipulate variables and thinking to myself, “Man – if I could just run some Python code on this it would be way easier”.  As luck would have it, you can!  Ansible supports a whole slew of plugins but the type I want to talk about today are called filter plugins.  Filter plugins, in my opinion, are one of the easiest ways to manipulate your variables with native Python.  And once you know how to do it you’ll see that it opens up a whole realm of possibilities in your playbooks.  Some of the most popular filters that exist today were once custom filters that someone wrote and then contributed to Ansible.  The IP address (ipaddr) filter set is a great example of filters that can be used to manipulate IP related information.

When I first looked into writing a custom filter I found the Ansible documentation not very helpful.  It essentially points you to their GitHub repo where you can look at the current filters.  Since I learn best by example, let’s write a quick filter so you can see how easy it is to do…

Nothing to it right?  This file defines a single filter called ‘a_filter’.  When called it receives the variable being passed into it (the variable to the left of the pipe (|)), appends the string ‘ CRAZY NEW FILTER’ to it, and then returns the new variable.  Now the trick is where to put this file.  For now, let’s create a folder called ‘filter_plugins’ in the same location as your playbook.  So in my case, the file structure would look like this…

/home/user/my_playbook.yml
/home/user/filter_plugins/my_filters.py

So let’s go ahead and create a quick little test playbook too…

This is a pretty simply playbook.  All it does is use the debug module to output a variable.  However, note that instead of just outputting the word ‘test’, we’re wrapping it in double curly braces like we do for any normal Ansible variable and we’re also piping it to ‘a_filter’.   The piping piece is what’s typically used to pass the variable to any of the predefined, or built-in, filters.  In this case, we’re piping the variable to our own custom filter.

This playbook assumes that you’ve told Ansible to use a local connection when talking to the locahost.  To do this, you need to set the ‘ansible_connection’ variable for the localhost to ‘local’ in your Ansible host file…

Once this is set, and you have both the playbook and the filter files in place, we can try running the playbook…

As you can see, the filter worked as expected.  The variable ‘test’ was passed to our custom filter where it was then modified and returned.  Pretty slick huh?  This is a uber simple example but it shows just how easy it is to inject custom Python functionality into your playbooks.  You’ll notice that in this example, there was only one variable passed to our function.  In this case, it was the variable to the left of the pipe.  In the case of filters, that will always be your first variable however, you can always add more.  For instance, let’s add a new filter to our function like this…

There are a couple of interesting things to point out in our new my_filters.py file.  First off – you’ll notice that we added another Python function called ‘b_filter’.  Its worthwhile to point out that your filter names don’t need to match your function names.  Down in the filters function at the bottom you’ll notice that we map the filter name ‘another_filter’ to the Python function ‘b_filter’.  You’ll also notice that the function b_filter takes 3 arguments.  The first will be the variable to the left of the pipe and the remaining need to be passed directly to the function as we’d normally pass variables.  For example…

Here you can see that we pass the second and third variables to the filter just like we’d normally pass variables to a function.  And while these examples only show doing this with strings, you can pass many other Python data types such as lists and dicts as well.

Lastly – I want to talk about the location of the filters.  By default, Ansible will look in the directory your playbook is located for a folder called ‘filter_plugins’ and load any filters it finds in that folder.  While this works, I don’t particularly care for this as I find it confusing for when you’re moving around playbooks.  I prefer to tell Ansible to look elsewhere for the filters.  To do this, we can edit the /etc/ansible/ansible.cfg file and uncomment and update the ‘filter_plugins’ parameter with your new location.

As you can see, filter plugins make it ridiculously easy to get your variables into native Python for manipulation.  Keep in mind that there are LOTS of default filter plugins so before you go crazy search the documentation to see if what you want already exists.

One of the fist things you’ll most likely encounter with Python are the datatypes lists and dicts.  While they initially seem quite simple, things can get awfully complex, awfully fast when you start intermingling the two datatypes.  So we’ll start with the basics, then dive into some more complex examples. 

Lists
Lists are defined as ‘a collection of different pieces of information as a sequence under a single variable name’.  So that’s a fancy way of saying it’s just a list.  In Python, lists are defined by using the ‘[]’ brackets.  So for example…

Items in lists can be accessed by index.  For example…

We can also iterate through the list with a simple loop…

Lists can be added to by using the list attribute ‘append’.  For instance…

Additionally, lists can contain items of multiple different types…

Dicts
Dicts are more of a ‘key/value’ kind of arrangement.  Like lists, they are mutable, and can be initialized with data or empty.  The major difference in definition is that dicts use ‘{}’ whereas lists used ‘[]’.  For example…

You might have noticed that we’re just printing the values.  If you need to print the key, you can do so as well but that doesn’t need to be returned from the dict since you’re using it to find the value.  So you can either just print it, or you can iterate through the items in the dict using a for loop and return both the key and the value…

Getting more complicated
Note that above the dict is holding different kinds of value.  ‘Langemak’ was type string and ‘30’ was type integer.  This means that dicts can hold a variety of different datatypes including lists!  Let’s take a quick example so you can see what I mean…

Conversely, lists can hold a variety of datatypes such as dicts…

So you can see that I can store multiple types of data in a dictionary.  When we print the data out our for loop needs to check and see what type of data the value matching the key holds.  For the values that are lists we execute an additional loop to run through the entire list.  So this is pretty easy to understand, but take a look at this example that I came across when I experimenting with a network switch API…

image
Interestingly enough, Python sees the ‘[‘ and interprets that this is a list.  Lists are delineated by commas and defined within brackets.  So if we look at this, we can see that what we really have is a one list, with one item in it.  What’s more interesting is that the lists single item is a dict.  We can see this by using the following code…

We can see that Python sees the lists one object as a dict.  What’s more interesting is that what we really have is a bunch of nested dicts…

image So in this example, the first dict has a key of ‘vrfs’ and a value of ‘test’ which happens to be another dict.  The dict ‘test’ has 4 key/value pairs with keys ‘asn’, ‘peers’, ‘routerId’, and ‘vrf’.  Then from there each peer value is also a dict which contain more key/value pairs describing the given peer.  We can get an idea of how you access each of the dicts by looking at this example which returns how many keys are in each nested dict…

So as you can see, you lists and dicts in Python can be pretty flexible.  Next up, more Python!

Python and IPython

I recently came across IPython while reading some Python development blogs.  IPython is an alternative to the standard Python shell that offers some additional features.  When I first read about IPython, I was a little confused because many people refer to it as the ‘Python interactive shell’.  While IPython is an interactive shell, it is not the Python interactive shell.  For instance, we can enter the Python interactive shell just by typing ‘python’ on our Python development box…

image
So, what we really did here was invoke the Python interpreter in interactive mode.  In this mode, commands can be read from the TTY and directly interpreted.  So for example, we can do something like this…

image
The Python code we type is directly interpreted and we get the output we would expect.  So instead of using the Python interpreter to run a .py script, we could do it all directly from the interpreter.  So the example from our Python up and running post works just as well in interactive mode as it did when run as a script…

image
So that’s Python interactive mode.  Now, let’s talk about IPython.  The first thing we need to do is install IPython.  We can actually do this with PIP! 

Then to run it we just type ‘ipython’ instead of ‘python’…

image
So I think this sort of nicely sums up what IPython is.  It’s an enhanced version of interactive Python.  So what are the enhancements?  The big one for me is tab completion.  If I start typing my ‘hello world’ script into IPython, I can tab complete the commands…

image
So here I just hit tab and IPython pulls all the available modules (and other stuff) from the package pyfiglet.  This is pretty darn helpful if you’re testing out code or just playing around with modules.  It’s also super helpful if we want to look at an object in Python code.  For instance, if we continue our example the next line creates a object called’ ‘f’ of type Figlet.  After we create the object, we can tell what type it is by typing the object name followed by a question mark…

image 
Here we can get all kinds of info about the object.  In addition, we can get all of the objects attributes by using tab complete…

image 
So IPython is certainly more helpful than the normal Python interpreters interactive mode and likely something I’ll use as I continue to learn Python.  I would love to hear any other use cases people have for IPython as well!  I’m sure there are other features I have yet to uncover. 

« Older entries