CloudShare ❤️ Ansible

Are you using Ansible to manage your servers?

High-five! 🙏 We use it, too.

If you’re not familiar with Ansible, it is similar to Chef or Puppet, but for people who prefer Python over Ruby or whatever language Puppet currently favors. One of its advantages is that it does not require anything except SSH to already be installed on the remote machine on which it operates. It is also simpler, and, some may say, easier to get started with than the alternatives.

Dynamic Inventory

The first step in using Ansible to configure servers is to get a list of those servers: their hostnames, login credentials, etc. The simplest way of doing so is with CloudShare’s dynamic inventory script. It uses CloudShare’s REST API and Python SDK behind the scenes to dynamically fetch a list of all your CloudShare environments and VM login credentials.

Setup

  1. Download cloudshare-inv.py – this is the dynamic inventory script.
  2. Install the cloudshare Python SDK: pip install cloudshare.
  3. Define your CloudShare API keys an environment variables: CLOUDSHARE_API_ID, CLOUDSHARE_API_KEY. You can grab them here.

That’s it. You are good to go.

Example – Running a Playbook

Let’s say you have a playbook called web-app.yml that you wish to run on one your VMs. Using the dynamic inventory, you can just do this:

ansible-playbook -i cloudshare-inventory.py all web-app.yml

This will run the playbook on all your VMs. You’d probably want to limit it to a subset of your VMs, and you can use --limit for that and pass it a specific environment name, a pattern of VM names, etc.

Run the inventory script on its own to see the list of servers groups and host names it generates for you. It spits out a very readable JSON document that looks like this:

{
  "docker-templates": {
    "hosts": [
      "ubuntu-14-04-server-64-bit-small",
      "ubuntu-14-04-server-64-bit-medium",
      "ubuntu-14-04-server-64-bit-large",
      "ubuntu-16-04-lts-server-small",
      "ubuntu-16-04-lts-server-medium",
      "ubuntu-16-04-lts-server-large"
    ]
  },
  "_meta": {
    "hostvars": {
        "login credentials": "will be populated here..."
    }
  }
}

Here we have one environment called docker-templates with six VMs.

Example – Running Ad-Hoc Commands

Something you probably find yourself doing from time to time is to apply patches to your servers.

In this example we have an environment called chat-demo containing a few Ubuntu Linux VMs, and we want to run apt-get upgrade on all of them. This is a one-liner in Ansible:

ansible -i cloudshare-inv.py chat-demo -m apt -a "upgrade=dist"

More Ansible

Check out the Ansible dynamic inventory repo. If you’d like us to integrate more deeply with Ansible, feel free to open a feature request issue and let us know.