Skip to content

Commit

Permalink
Added digitalocean dynamic inventory script
Browse files Browse the repository at this point in the history
  • Loading branch information
2bithacker committed May 5, 2016
1 parent eee197e commit 271e5c2
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 3 deletions.
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
# ansible-modules
Various Ansible modules

## sysrc
## Inventory

### digitalocean

A dynamic inventory script for DigitalOcean droplets. All droplets are placed in a 'droplet' group
as well as grouped by individual droplet tags. Also, `ansible_ssh_host` is set for each host to the
public IPv4 address of the droplet. This is significantly different from the stock `digital_ocean.py`
inventory module.

## Facts

### sysrc

A facts gathering module for FreeBSD's `sysrc` utility, which mostly grabs the variables set in /etc/rc.conf

Expand All @@ -23,7 +34,7 @@ somehost.example | success >> {
}
```

## zfs_facts
### zfs_facts

Facts module to collect information on existing zpools and zfs filesystems.

Expand Down Expand Up @@ -59,7 +70,7 @@ somehost.example | success >> {
}
```

## do_metadata
### do_metadata

All of the information from the [DigitalOcean Metadata API](https://developers.digitalocean.com/documentation/metadata/) dumped into Ansible facts.

Expand Down
90 changes: 90 additions & 0 deletions inventory/digitalocean.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env python2.7

import urllib2
import json
import ConfigParser
import argparse
import os
import collections


class DigitalOceanInventory(object):
def __init__(self):
self.conf = ConfigParser.SafeConfigParser()
self.args = None

self.api_token = None

def read_config(self):
self.conf.read(os.path.dirname(
os.path.realpath(__file__)) + '/digitalocean.ini')
self.api_token = self.conf.get('digitalocean', 'api_token')
return self.conf

def parse_args(self):
parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true',
help='List all droplets')
group.add_argument('--host', help='Get information on single host')

parser.add_argument('--token', help='DigitalOcean API token')

self.args = parser.parse_args()

if self.args.token:
self.api_token = self.args.token

def do_request(self, path):
req = urllib2.Request(url='https://api.digitalocean.com%s' % (path))
req.add_header('Content-type', 'application/json')
req.add_header('Authorization', 'Bearer '+self.api_token)
return urllib2.urlopen(req).read()

def get_hostlist(self):
jsondata = self.do_request('/v2/droplets')
self.hostlist = json.loads(jsondata)

def _pub_addr(self, host, ver=4):
for addr in host['networks']['v%d' % (ver)]:
if addr['type'] == 'public':
return addr['ip_address']

def output_hostlist(self):
groups = collections.defaultdict(lambda: {'hosts': []})
groups['_meta'] = {'hostvars': {}}
hostvars = groups['_meta']['hostvars']

for host in self.hostlist['droplets']:
hostname = host['name']

# All hosts go in the 'droplet' group
groups['droplet']['hosts'].append(hostname)

# Also group hosts by their tags
for tag in host['tags']:
groups[tag]['hosts'].append(hostname)

# Add IP address to hostvars
hostvars[hostname] = {
'ansible_ssh_host': self._pub_addr(host)
}

print json.dumps(groups)

def output_host(self):
pass

def output(self):
if self.args.list:
self.output_hostlist()
if self.args.host:
self.output_host()

if __name__ == '__main__':
doi = DigitalOceanInventory()
doi.read_config()
doi.parse_args()
doi.get_hostlist()
doi.output()

0 comments on commit 271e5c2

Please sign in to comment.