Easier CLI for ad-hoc Ansible tasks and playbooks

This article is about using Ansible on the command-line.


You …

A Possible Solution

Taking a page from old school Posix tools, let’s make a script that encodes Ansible group names into the filename.

Then you can go from this:

$ ansible atlanta -m copy -a "src=/etc/hosts dest=/tmp/hosts"
$ ansible webservers -m service -a "name=httpd state=started"

To this:

$ atlanta copy "src=/etc/hosts dest=/tmp/hosts"
$ webservers service "name=https state=started"

Or from this:

$ ansible-playbook -l atlanta go-to-the-moon
$ ansible-playbook -l webservers do-the-other-things

To this:

$ atlanta go-to-the-moon
$ webservers do-the-other-things

Setting Up

These are just examples. Please don’t spend time bikeshedding names because you can use whichever names you like.

  1. Download the contents of ansible-by-proxy from here. It’s a starter script that includes a bunch of sensible settings expressed via environment variables. Remove or change these to match your needs.

    Note that the script expects to find a sub-directory called ansible in the same directory as the script which contains the playbooks and the inventory file.

  2. Store this file somewhere on the system PATH.

    Don’t forget to mark the file as executable if it isn’t already.

    $ chmod +x ansible-by-proxy
  3. Create symlinks to the file that have the same name as hostnames or groups as described in the includes:

    $ ln -s ansible-by-proxy atlanta
    $ ln -s ansible-by-proxy webservers

    and so on.

That’s it. Now you can invoke playbooks and tasks just by using the name of host or group.