Major rename of package from lib to ansibleworks.

This commit is contained in:
Chris Church
2013-05-21 18:20:26 -04:00
parent 5133b9a30e
commit aeac739735
264 changed files with 230 additions and 316 deletions

View File

@@ -0,0 +1,2 @@
# Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.

View File

@@ -0,0 +1,39 @@
# Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
import os
import sys
def run_command_as_script(command_name):
'''
Helper function to run the given management command directly as a script.
Include something like the following in your management/commands/blah.py:
if __name__ == '__main__':
from __init__ import run_command_as_script
command_name = os.path.splitext(os.path.basename(__file__))[0]
run_command_as_script(command_name)
'''
# The DJANGO_SETTINGS_MODULE environment variable should already be set if
# the script is called from a celery task. Don't attemtp to set a default.
settings_module_name = os.environ['DJANGO_SETTINGS_MODULE']
# This sys.path hack is needed when a celery task calls ansible-playbook
# and needs to execute the script directly. FIXME: Figure out if this will
# work when installed in a production environment.
try:
settings_module = __import__(settings_module_name, globals(), locals(),
[settings_module_name.split('.')[-1]])
except ImportError:
top_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..')
sys.path.insert(0, os.path.abspath(top_dir))
settings_module = __import__(settings_module_name, globals(), locals(),
[settings_module_name.split('.')[-1]])
# Use the ACOM_TEST_DATABASE_NAME environment variable to specify the test
# database name when called from unit tests.
if os.environ.get('ACOM_TEST_DATABASE_NAME', None):
settings_module.DATABASES['default']['NAME'] = os.environ['ACOM_TEST_DATABASE_NAME']
from django.core.management import execute_from_command_line
argv = [sys.argv[0], command_name] + sys.argv[1:]
execute_from_command_line(argv)

View File

@@ -0,0 +1,76 @@
#!/usr/bin/env python
# Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
import json
from optparse import make_option
import os
import sys
from django.core.management.base import NoArgsCommand, CommandError
class Command(NoArgsCommand):
'''
Management command to log callback events from ansible-playbook.
'''
help = 'Ansible Commander Callback Event Capture'
option_list = NoArgsCommand.option_list + (
make_option('-j', '--job', dest='job_id',
type='int', default=0,
help='Job ID (can also be specified using ACOM_JOB_ID '
'environment variable)'),
make_option('-e', '--event', dest='event_type', default=None,
help='Event type'),
make_option('-f', '--file', dest='event_data_file', default=None,
help='JSON-formatted data file containing callback event '
'data (specify "-" to read from stdin)'),
make_option('-d', '--data', dest='event_data_json', default=None,
help='JSON-formatted callback event data'),
)
def handle_noargs(self, **options):
from ansibleworks.main.models import Job, JobEvent
event_type = options.get('event_type', None)
if not event_type:
raise CommandError('No event specified')
if event_type not in [x[0] for x in JobEvent.EVENT_TYPES]:
raise CommandError('Unsupported event')
event_data_file = options.get('event_data_file', None)
event_data_json = options.get('event_data_json', None)
if event_data_file is None and event_data_json is None:
raise CommandError('Either --file or --data must be specified')
try:
job_id = int(os.getenv('ACOM_JOB_ID', options.get('job_id', 0)))
except ValueError:
raise CommandError('Job ID must be an integer')
if not job_id:
raise CommandError('No Job ID specified')
try:
job = Job.objects.get(id=job_id)
except Job.DoesNotExist:
raise CommandError('Job with ID %d not found' % job_id)
if job.status != 'running':
raise CommandError('Unable to add event except when job is running'
', status is currently %s' % job.status)
try:
if event_data_json is None:
try:
if event_data_file == '-':
event_data_fileobj = sys.stdin
else:
event_data_fileobj = file(event_data_file, 'rb')
event_data = json.load(event_data_fileobj)
except IOError, e:
raise CommandError('Error %r reading from %s' % (e, event_data_file))
else:
event_data = json.loads(event_data_json)
except ValueError:
raise CommandError('Error parsing JSON data')
job.job_events.create(event=event_type, event_data=event_data)
if __name__ == '__main__':
from __init__ import run_command_as_script
command_name = os.path.splitext(os.path.basename(__file__))[0]
run_command_as_script(command_name)

View File

@@ -0,0 +1,93 @@
#!/usr/bin/env python
# Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
import json
from optparse import make_option
import os
from django.core.management.base import NoArgsCommand, CommandError
class Command(NoArgsCommand):
help = 'Ansible Commander Inventory script'
option_list = NoArgsCommand.option_list + (
make_option('-i', '--inventory', dest='inventory_id', type='int',
default=0, help='Inventory ID (can also be specified using'
' ACOM_INVENTORY_ID environment variable)'),
make_option('--list', action='store_true', dest='list', default=False,
help='Return JSON hash of host groups.'),
make_option('--host', dest='host', default='',
help='Return JSON hash of host vars.'),
make_option('--indent', dest='indent', type='int', default=None,
help='Indentation level for pretty printing output'),
)
def get_list(self, inventory, indent=None):
groups = {}
for group in inventory.groups.all():
# FIXME: Check if group is active?
group_info = {
'hosts': list(group.hosts.values_list('name', flat=True)),
'children': list(group.children.values_list('name', flat=True)),
}
if group.variable_data is not None:
group_info['vars'] = json.loads(group.variable_data.data)
group_info = dict(filter(lambda x: bool(x[1]), group_info.items()))
if group_info.keys() in ([], ['hosts']):
groups[group.name] = group_info.get('hosts', [])
else:
groups[group.name] = group_info
self.stdout.write(json.dumps(groups, indent=indent))
def get_host(self, inventory, hostname, indent=None):
from ansibleworks.main.models import Host
hostvars = {}
try:
# FIXME: Check if active?
host = inventory.hosts.get(name=hostname)
except Host.DoesNotExist:
raise CommandError('Host %s not found in the given inventory' % hostname)
hostvars = {}
if host.variable_data is not None:
hostvars = json.loads(host.variable_data.data)
self.stdout.write(json.dumps(hostvars, indent=indent))
def handle_noargs(self, **options):
try:
from ansibleworks.main.models import Inventory
try:
# Command line argument takes precedence over environment
# variable.
inventory_id = int(options.get('inventory_id', 0) or \
os.getenv('ACOM_INVENTORY_ID', 0))
except ValueError:
raise CommandError('Inventory ID must be an integer')
if not inventory_id:
raise CommandError('No inventory ID specified')
try:
inventory = Inventory.objects.get(id=inventory_id)
except Inventory.DoesNotExist:
raise CommandError('Inventory with ID %d not found' % inventory_id)
host = options.get('host', '')
list_ = options.get('list', False)
indent = options.get('indent', None)
if list_ and host:
raise CommandError('Only one of --list or --host can be specified')
elif list_:
self.get_list(inventory, indent=indent)
elif host:
self.get_host(inventory, host, indent=indent)
else:
raise CommandError('Either --list or --host must be specified')
except CommandError, e:
# Always return an empty hash on stdout, even when an error occurs.
self.stdout.write(json.dumps({}))
raise
if __name__ == '__main__':
from __init__ import run_command_as_script
command_name = os.path.splitext(os.path.basename(__file__))[0]
run_command_as_script(command_name)