Commit fec9b8a5 by Brian Coca

Merge pull request #10885 from bcoca/galaxy_v2

revamped base CLI and moved galaxy to it's own classes/api
parents b851ce29 ccc9a33b
...@@ -27,6 +27,7 @@ New Modules: ...@@ -27,6 +27,7 @@ New Modules:
* cloudstack: cs_securitygroup_rule * cloudstack: cs_securitygroup_rule
* cloudstack: cs_vmsnapshot * cloudstack: cs_vmsnapshot
* maven_artifact * maven_artifact
* openstack: os_server_facts
* pushover * pushover
* zabbix_host * zabbix_host
* zabbix_hostmacro * zabbix_hostmacro
......
...@@ -40,13 +40,15 @@ def get_config(p, section, key, env_var, default, boolean=False, integer=False, ...@@ -40,13 +40,15 @@ def get_config(p, section, key, env_var, default, boolean=False, integer=False,
''' return a configuration variable with casting ''' ''' return a configuration variable with casting '''
value = _get_config(p, section, key, env_var, default) value = _get_config(p, section, key, env_var, default)
if boolean: if boolean:
return mk_boolean(value) value = mk_boolean(value)
if value and integer: if value:
return int(value) if integer:
if value and floating: value = int(value)
return float(value) elif floating:
if value and islist: value = float(value)
return [x.strip() for x in value.split(',')] elif islist:
if isinstance(value, basestring):
value = [x.strip() for x in value.split(',')]
return value return value
def _get_config(p, section, key, env_var, default): def _get_config(p, section, key, env_var, default):
...@@ -104,7 +106,7 @@ DEFAULTS='defaults' ...@@ -104,7 +106,7 @@ DEFAULTS='defaults'
# configurable things # configurable things
DEFAULT_DEBUG = get_config(p, DEFAULTS, 'debug', 'ANSIBLE_DEBUG', False, boolean=True) DEFAULT_DEBUG = get_config(p, DEFAULTS, 'debug', 'ANSIBLE_DEBUG', False, boolean=True)
DEFAULT_HOST_LIST = shell_expand_path(get_config(p, DEFAULTS, 'inventory', 'ANSIBLE_INVENTORY', get_config(p, DEFAULTS,'hostfile','ANSIBLE_HOSTS', '/etc/ansible/hosts'))) DEFAULT_HOST_LIST = shell_expand_path(get_config(p, DEFAULTS, 'hostfile', 'ANSIBLE_HOSTS', get_config(p, DEFAULTS,'inventory','ANSIBLE_INVENTORY', '/etc/ansible/hosts')))
DEFAULT_MODULE_PATH = get_config(p, DEFAULTS, 'library', 'ANSIBLE_LIBRARY', None) DEFAULT_MODULE_PATH = get_config(p, DEFAULTS, 'library', 'ANSIBLE_LIBRARY', None)
DEFAULT_ROLES_PATH = shell_expand_path(get_config(p, DEFAULTS, 'roles_path', 'ANSIBLE_ROLES_PATH', '/etc/ansible/roles')) DEFAULT_ROLES_PATH = shell_expand_path(get_config(p, DEFAULTS, 'roles_path', 'ANSIBLE_ROLES_PATH', '/etc/ansible/roles'))
DEFAULT_REMOTE_TMP = get_config(p, DEFAULTS, 'remote_tmp', 'ANSIBLE_REMOTE_TEMP', '$HOME/.ansible/tmp') DEFAULT_REMOTE_TMP = get_config(p, DEFAULTS, 'remote_tmp', 'ANSIBLE_REMOTE_TEMP', '$HOME/.ansible/tmp')
...@@ -203,10 +205,16 @@ ACCELERATE_KEYS_FILE_PERMS = get_config(p, 'accelerate', 'accelerate_keys_fi ...@@ -203,10 +205,16 @@ ACCELERATE_KEYS_FILE_PERMS = get_config(p, 'accelerate', 'accelerate_keys_fi
ACCELERATE_MULTI_KEY = get_config(p, 'accelerate', 'accelerate_multi_key', 'ACCELERATE_MULTI_KEY', False, boolean=True) ACCELERATE_MULTI_KEY = get_config(p, 'accelerate', 'accelerate_multi_key', 'ACCELERATE_MULTI_KEY', False, boolean=True)
PARAMIKO_PTY = get_config(p, 'paramiko_connection', 'pty', 'ANSIBLE_PARAMIKO_PTY', True, boolean=True) PARAMIKO_PTY = get_config(p, 'paramiko_connection', 'pty', 'ANSIBLE_PARAMIKO_PTY', True, boolean=True)
# galaxy related
DEFAULT_GALAXY_URI = get_config(p, 'galaxy', 'server_uri', 'ANSIBLE_GALAXY_SERVER_URI', 'https://galaxy.ansible.com')
# this can be configured to blacklist SCMS but cannot add new ones unless the code is also updated
GALAXY_SCMS = get_config(p, 'galaxy', 'scms', 'ANSIBLE_GALAXY_SCMS', ['git','hg'], islist=True)
# characters included in auto-generated passwords # characters included in auto-generated passwords
DEFAULT_PASSWORD_CHARS = ascii_letters + digits + ".,:-_" DEFAULT_PASSWORD_CHARS = ascii_letters + digits + ".,:-_"
# non-configurable things # non-configurable things
MODULE_REQUIRE_ARGS = ['command', 'shell', 'raw', 'script']
DEFAULT_BECOME_PASS = None DEFAULT_BECOME_PASS = None
DEFAULT_SUDO_PASS = None DEFAULT_SUDO_PASS = None
DEFAULT_REMOTE_PASS = None DEFAULT_REMOTE_PASS = None
......
...@@ -140,6 +140,10 @@ class AnsibleError(Exception): ...@@ -140,6 +140,10 @@ class AnsibleError(Exception):
return error_message return error_message
class AnsibleOptionsError(AnsibleError):
''' bad or incomplete options passed '''
pass
class AnsibleParserError(AnsibleError): class AnsibleParserError(AnsibleError):
''' something was detected early that is wrong about a playbook or data file ''' ''' something was detected early that is wrong about a playbook or data file '''
pass pass
...@@ -164,6 +168,14 @@ class AnsibleFilterError(AnsibleRuntimeError): ...@@ -164,6 +168,14 @@ class AnsibleFilterError(AnsibleRuntimeError):
''' a templating failure ''' ''' a templating failure '''
pass pass
class AnsibleLookupError(AnsibleRuntimeError):
''' a lookup failure '''
pass
class AnsibleCallbackError(AnsibleRuntimeError):
''' a callback failure '''
pass
class AnsibleUndefinedVariable(AnsibleRuntimeError): class AnsibleUndefinedVariable(AnsibleRuntimeError):
''' a templating failure ''' ''' a templating failure '''
pass pass
...@@ -171,7 +183,3 @@ class AnsibleUndefinedVariable(AnsibleRuntimeError): ...@@ -171,7 +183,3 @@ class AnsibleUndefinedVariable(AnsibleRuntimeError):
class AnsibleFileNotFound(AnsibleRuntimeError): class AnsibleFileNotFound(AnsibleRuntimeError):
''' a file missing failure ''' ''' a file missing failure '''
pass pass
class AnsibleParserError(AnsibleRuntimeError):
''' a parser error '''
pass
########################################################################
#
# (C) 2015, Brian Coca <bcoca@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
''' This manages remote shared Ansible objects, mainly roles'''
import os
from ansible.errors import AnsibleError
from ansible.utils.display import Display
# default_readme_template
# default_meta_template
class Galaxy(object):
''' Keeps global galaxy info '''
def __init__(self, options, display=None):
if display is None:
self.display = Display()
else:
self.display = display
self.options = options
self.roles_path = getattr(self.options, 'roles_path', None)
if self.roles_path:
self.roles_path = os.path.expanduser(self.roles_path)
self.roles = {}
# load data path for resource usage
this_dir, this_filename = os.path.split(__file__)
self.DATA_PATH = os.path.join(this_dir, "data")
#TODO: move to getter for lazy loading
self.default_readme = self._str_from_data_file('readme')
self.default_meta = self._str_from_data_file('metadata_template.j2')
def add_role(self, role):
self.roles[role.name] = role
def remove_role(self, role_name):
del self.roles[role_name]
def _str_from_data_file(self, filename):
myfile = os.path.join(self.DATA_PATH, filename)
try:
return open(myfile).read()
except Exception as e:
raise AnsibleError("Could not open %s: %s" % (filename, str(e)))
#!/usr/bin/env python
########################################################################
#
# (C) 2013, James Cammarata <jcammarata@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
import json
from urllib2 import urlopen, quote as urlquote
from urlparse import urlparse
from ansible.errors import AnsibleError
class GalaxyAPI(object):
''' This class is meant to be used as a API client for an Ansible Galaxy server '''
SUPPORTED_VERSIONS = ['v1']
def __init__(self, galaxy, api_server):
self.galaxy = galaxy
try:
urlparse(api_server, scheme='https')
except:
raise AnsibleError("Invalid server API url passed: %s" % api_server)
server_version = self.get_server_api_version('%s/api/' % (api_server))
if not server_version:
raise AnsibleError("Could not retrieve server API version: %s" % api_server)
if server_version in self.SUPPORTED_VERSIONS:
self.baseurl = '%s/api/%s' % (api_server, server_version)
self.version = server_version # for future use
self.galaxy.display.vvvvv("Base API: %s" % self.baseurl)
else:
raise AnsibleError("Unsupported Galaxy server API version: %s" % server_version)
def get_server_api_version(self, api_server):
"""
Fetches the Galaxy API current version to ensure
the API server is up and reachable.
"""
#TODO: fix galaxy server which returns current_version path (/api/v1) vs actual version (v1)
# also should set baseurl using supported_versions which has path
return 'v1'
try:
data = json.load(urlopen(api_server))
return data.get("current_version", 'v1')
except Exception as e:
# TODO: report error
return None
def lookup_role_by_name(self, role_name, notify=True):
"""
Find a role by name
"""
role_name = urlquote(role_name)
try:
parts = role_name.split(".")
user_name = ".".join(parts[0:-1])
role_name = parts[-1]
if notify:
self.galaxy.display.display("- downloading role '%s', owned by %s" % (role_name, user_name))
except:
raise AnsibleError("- invalid role name (%s). Specify role as format: username.rolename" % role_name)
url = '%s/roles/?owner__username=%s&name=%s' % (self.baseurl, user_name, role_name)
self.galaxy.display.vvvv("- %s" % (url))
try:
data = json.load(urlopen(url))
if len(data["results"]) != 0:
return data["results"][0]
except:
# TODO: report on connection/availability errors
pass
return None
def fetch_role_related(self, related, role_id):
"""
Fetch the list of related items for the given role.
The url comes from the 'related' field of the role.
"""
try:
url = '%s/roles/%d/%s/?page_size=50' % (self.baseurl, int(role_id), related)
data = json.load(urlopen(url))
results = data['results']
done = (data.get('next', None) == None)
while not done:
url = '%s%s' % (self.baseurl, data['next'])
self.galaxy.display.display(url)
data = json.load(urlopen(url))
results += data['results']
done = (data.get('next', None) == None)
return results
except:
return None
def get_list(self, what):
"""
Fetch the list of items specified.
"""
try:
url = '%s/%s/?page_size' % (self.baseurl, what)
data = json.load(urlopen(url))
if "results" in data:
results = data['results']
else:
results = data
done = True
if "next" in data:
done = (data.get('next', None) == None)
while not done:
url = '%s%s' % (self.baseurl, data['next'])
self.galaxy.display.display(url)
data = json.load(urlopen(url))
results += data['results']
done = (data.get('next', None) == None)
return results
except Exception as error:
raise AnsibleError("Failed to download the %s list: %s" % (what, str(error)))
galaxy_info:
author: {{ author }}
description: {{description}}
company: {{ company }}
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: {{ issue_tracker_url }}
# Some suggested licenses:
# - BSD (default)
# - MIT
# - GPLv2
# - GPLv3
# - Apache
# - CC-BY
license: {{ license }}
min_ansible_version: {{ min_ansible_version }}
#
# Below are all platforms currently available. Just uncomment
# the ones that apply to your role. If you don't see your
# platform on this list, let us know and we'll get it added!
#
#platforms:
{%- for platform,versions in platforms.iteritems() %}
#- name: {{ platform }}
# versions:
# - all
{%- for version in versions %}
# - {{ version }}
{%- endfor %}
{%- endfor %}
#
# Below are all categories currently available. Just as with
# the platforms above, uncomment those that apply to your role.
#
#categories:
{%- for category in categories %}
#- {{ category.name }}
{%- endfor %}
dependencies: []
# List your role dependencies here, one per line.
# Be sure to remove the '[]' above if you add dependencies
# to this list.
{% for dependency in dependencies %}
#- {{ dependency }}
{% endfor %}
Role Name
=========
A brief description of the role goes here.
Requirements
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
Role Variables
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
Dependencies
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
Example Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
License
-------
BSD
Author Information
------------------
An optional section for the role authors to include contact information, or a website (HTML is not allowed).
...@@ -203,7 +203,7 @@ class VaultEditor(object): ...@@ -203,7 +203,7 @@ class VaultEditor(object):
_, tmp_path = tempfile.mkstemp() _, tmp_path = tempfile.mkstemp()
if existing_data: if existing_data:
self.write_data(data, tmp_path) self.write_data(existing_data, tmp_path)
# drop the user into an editor on the tmp file # drop the user into an editor on the tmp file
call(self._editor_shell_command(tmp_path)) call(self._editor_shell_command(tmp_path))
......
...@@ -37,6 +37,8 @@ class CallbackModule(CallbackBase): ...@@ -37,6 +37,8 @@ class CallbackModule(CallbackBase):
pass pass
def v2_runner_on_failed(self, result, ignore_errors=False): def v2_runner_on_failed(self, result, ignore_errors=False):
if 'exception' in result._result and self._display.verbosity < 3:
del result._result['exception']
self._display.display("fatal: [%s]: FAILED! => %s" % (result._host.get_name(), json.dumps(result._result, ensure_ascii=False)), color='red') self._display.display("fatal: [%s]: FAILED! => %s" % (result._host.get_name(), json.dumps(result._result, ensure_ascii=False)), color='red')
def v2_runner_on_ok(self, result): def v2_runner_on_ok(self, result):
......
...@@ -38,6 +38,8 @@ class CallbackModule(CallbackBase): ...@@ -38,6 +38,8 @@ class CallbackModule(CallbackBase):
pass pass
def v2_runner_on_failed(self, result, ignore_errors=False): def v2_runner_on_failed(self, result, ignore_errors=False):
if 'exception' in result._result and self._display.verbosity < 3:
del result._result['exception']
self._display.display("%s | FAILED! => %s" % (result._host.get_name(), result._result), color='red') self._display.display("%s | FAILED! => %s" % (result._host.get_name(), result._result), color='red')
def v2_runner_on_ok(self, result): def v2_runner_on_ok(self, result):
......
...@@ -23,7 +23,7 @@ import textwrap ...@@ -23,7 +23,7 @@ import textwrap
import sys import sys
from ansible import constants as C from ansible import constants as C
from ansible.errors import * from ansible.errors import AnsibleError
from ansible.utils.color import stringc from ansible.utils.color import stringc
class Display: class Display:
...@@ -35,6 +35,7 @@ class Display: ...@@ -35,6 +35,7 @@ class Display:
# list of all deprecation messages to prevent duplicate display # list of all deprecation messages to prevent duplicate display
self._deprecations = {} self._deprecations = {}
self._warns = {} self._warns = {}
self._errors = {}
def display(self, msg, color=None, stderr=False, screen_only=False, log_only=False): def display(self, msg, color=None, stderr=False, screen_only=False, log_only=False):
msg2 = msg msg2 = msg
...@@ -83,7 +84,7 @@ class Display: ...@@ -83,7 +84,7 @@ class Display:
if host is None: if host is None:
self.display(msg, color='blue') self.display(msg, color='blue')
else: else:
self.display("<%s> %s" % (host, msg), color='blue') self.display("<%s> %s" % (host, msg), color='blue', screen_only=True)
def deprecated(self, msg, version, removed=False): def deprecated(self, msg, version, removed=False):
''' used to print out a deprecation message.''' ''' used to print out a deprecation message.'''
...@@ -130,3 +131,12 @@ class Display: ...@@ -130,3 +131,12 @@ class Display:
star_len = 3 star_len = 3
stars = "*" * star_len stars = "*" * star_len
self.display("\n%s %s" % (msg, stars), color=color) self.display("\n%s %s" % (msg, stars), color=color)
def error(self, msg):
new_msg = "\n[ERROR]: %s" % msg
wrapped = textwrap.wrap(new_msg, 79)
new_msg = "\n".join(wrapped) + "\n"
if new_msg not in self._errors:
self.display(new_msg, color='red', stderr=True)
self._errors[new_msg] = 1
...@@ -40,28 +40,20 @@ from ansible.inventory import Inventory ...@@ -40,28 +40,20 @@ from ansible.inventory import Inventory
from ansible.parsing import DataLoader from ansible.parsing import DataLoader
from ansible.parsing.splitter import parse_kv from ansible.parsing.splitter import parse_kv
from ansible.playbook.play import Play from ansible.playbook.play import Play
from ansible.utils.display import Display from ansible.utils.cli import CLI
from ansible.utils.cli import base_parser, validate_conflicts, normalize_become_options, ask_passwords
from ansible.utils.display import Display from ansible.utils.display import Display
from ansible.utils.vault import read_vault_file from ansible.utils.vault import read_vault_file
from ansible.vars import VariableManager from ansible.vars import VariableManager
######################################################## ########################################################
class Cli(object): class AdHocCli(CLI):
''' code behind bin/ansible ''' ''' code behind ansible ad-hoc cli'''
def __init__(self, display=None):
if display is None:
self.display = Display()
else:
self.display = display
def parse(self): def parse(self):
''' create an options parser for bin/ansible ''' ''' create an options parser for bin/ansible '''
parser = base_parser( self.parser = CLI.base_parser(
usage='%prog <host-pattern> [options]', usage='%prog <host-pattern> [options]',
runas_opts=True, runas_opts=True,
async_opts=True, async_opts=True,
...@@ -71,102 +63,110 @@ class Cli(object): ...@@ -71,102 +63,110 @@ class Cli(object):
) )
# options unique to ansible ad-hoc # options unique to ansible ad-hoc
parser.add_option('-a', '--args', dest='module_args', self.parser.add_option('-a', '--args', dest='module_args',
help="module arguments", default=C.DEFAULT_MODULE_ARGS) help="module arguments", default=C.DEFAULT_MODULE_ARGS)
parser.add_option('-m', '--module-name', dest='module_name', self.parser.add_option('-m', '--module-name', dest='module_name',
help="module name to execute (default=%s)" % C.DEFAULT_MODULE_NAME, help="module name to execute (default=%s)" % C.DEFAULT_MODULE_NAME,
default=C.DEFAULT_MODULE_NAME) default=C.DEFAULT_MODULE_NAME)
options, args = parser.parse_args() self.options, self.args = self.parser.parse_args()
if len(args) == 0 or len(args) > 1: if len(self.args) != 1:
parser.print_help() self.parser.print_help()
sys.exit(1) sys.exit(1)
display.verbosity = options.verbosity self.display.verbosity = self.options.verbosity
validate_conflicts(parser,options) self.validate_conflicts()
return (options, args) return True
# ----------------------------------------------
def run(self, options, args): def run(self):
''' use Runner lib to do SSH things ''' ''' use Runner lib to do SSH things '''
pattern = args[0] # only thing left should be host pattern
pattern = self.args[0]
if options.connection == "local": # ignore connection password cause we are local
options.ask_pass = False if self.options.connection == "local":
self.options.ask_pass = False
sshpass = None sshpass = None
becomepass = None becomepass = None
vault_pass = None vault_pass = None
normalize_become_options(options) self.normalize_become_options()
(sshpass, becomepass, vault_pass) = ask_passwords(options) (sshpass, becomepass) = self.ask_passwords()
passwords = { 'conn_pass': sshpass, 'become_pass': becomepass } passwords = { 'conn_pass': sshpass, 'become_pass': becomepass }
if options.vault_password_file: if self.options.vault_password_file:
# read vault_pass from a file # read vault_pass from a file
vault_pass = read_vault_file(options.vault_password_file) vault_pass = read_vault_file(self.options.vault_password_file)
elif self.options.ask_vault_pass:
vault_pass = self.ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False)[0]
loader = DataLoader(vault_password=vault_pass) loader = DataLoader(vault_password=vault_pass)
variable_manager = VariableManager() variable_manager = VariableManager()
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=options.inventory) inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=self.options.inventory)
hosts = inventory.list_hosts(pattern) hosts = inventory.list_hosts(pattern)
if len(hosts) == 0: if len(hosts) == 0:
d = Display() self.display.warning("provided hosts list is empty, only localhost is available")
d.warning("provided hosts list is empty, only localhost is available")
if options.listhosts: if self.options.listhosts:
for host in hosts: for host in hosts:
self.display.display(' %s' % host.name) self.display.display(' %s' % host.name)
sys.exit(0) return 0
if ((options.module_name == 'command' or options.module_name == 'shell') and not options.module_args): if self.options.module_name in C.MODULE_REQUIRE_ARGS and not self.options.module_args:
raise AnsibleError("No argument passed to %s module" % options.module_name) raise AnsibleError("No argument passed to %s module" % self.options.module_name)
# FIXME: async support needed #TODO: implement async support
#if options.seconds: #if self.options.seconds:
# callbacks.display("background launch...\n\n", color='cyan') # callbacks.display("background launch...\n\n", color='cyan')
# results, poller = runner.run_async(options.seconds) # results, poller = runner.run_async(self.options.seconds)
# results = self.poll_while_needed(poller, options) # results = self.poll_while_needed(poller)
#else: #else:
# results = runner.run() # results = runner.run()
# create a pseudo-play to execute the specified module via a single task # create a pseudo-play to execute the specified module via a single task
play_ds = dict( play_ds = dict(
name = "Ansible Ad-Hoc",
hosts = pattern, hosts = pattern,
gather_facts = 'no', gather_facts = 'no',
tasks = [ tasks = [ dict(action=dict(module=self.options.module_name, args=parse_kv(self.options.module_args))), ]
dict(action=dict(module=options.module_name, args=parse_kv(options.module_args))),
]
) )
play = Play().load(play_ds, variable_manager=variable_manager, loader=loader) play = Play().load(play_ds, variable_manager=variable_manager, loader=loader)
# now create a task queue manager to execute the play # now create a task queue manager to execute the play
try: try:
display = Display() tqm = TaskQueueManager(
tqm = TaskQueueManager(inventory=inventory, variable_manager=variable_manager, loader=loader, display=display, options=options, passwords=passwords, stdout_callback='minimal') inventory=inventory,
callback='minimal',
variable_manager=variable_manager,
loader=loader,
display=self.display,
options=self.options,
passwords=passwords,
stdout_callback='minimal',
)
result = tqm.run(play) result = tqm.run(play)
tqm.cleanup() finally:
except AnsibleError: if tqm:
tqm.cleanup() tqm.cleanup()
raise
return result return result
# ---------------------------------------------- # ----------------------------------------------
def poll_while_needed(self, poller, options): def poll_while_needed(self, poller):
''' summarize results from Runner ''' ''' summarize results from Runner '''
# BACKGROUND POLL LOGIC when -B and -P are specified # BACKGROUND POLL LOGIC when -B and -P are specified
if options.seconds and options.poll_interval > 0: if self.options.seconds and self.options.poll_interval > 0:
poller.wait(options.seconds, options.poll_interval) poller.wait(self.options.seconds, self.options.poll_interval)
return poller.results return poller.results
...@@ -176,15 +176,17 @@ class Cli(object): ...@@ -176,15 +176,17 @@ class Cli(object):
if __name__ == '__main__': if __name__ == '__main__':
display = Display() display = Display()
#display.display(" ".join(sys.argv))
try: try:
cli = Cli(display=display) cli = AdHocCli(sys.argv, display=display)
(options, args) = cli.parse() cli.parse()
sys.exit(cli.run(options, args)) sys.exit(cli.run())
except AnsibleError as e: except AnsibleOptionsError as e:
display.display("[ERROR]: %s" % e, color='red', stderr=True) cli.parser.print_help()
display.display(str(e), stderr=True, color='red')
sys.exit(1) sys.exit(1)
except AnsibleError as e:
display.display(str(e), stderr=True, color='red')
sys.exit(2)
except KeyboardInterrupt: except KeyboardInterrupt:
display.display("[ERROR]: interrupted", color='red', stderr=True) display.error("interrupted")
sys.exit(1) sys.exit(4)
...@@ -33,143 +33,102 @@ import os ...@@ -33,143 +33,102 @@ import os
import sys import sys
import traceback import traceback
from ansible.errors import AnsibleError from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.parsing.vault import VaultEditor from ansible.parsing.vault import VaultEditor
from ansible.utils.cli import base_parser, ask_vault_passwords from ansible.utils.cli import CLI
from ansible.utils.display import Display
#------------------------------------------------------------------------------------- class VaultCli(CLI):
# Utility functions for parsing actions/options """ Vault command line class """
#-------------------------------------------------------------------------------------
class Cli(object):
VALID_ACTIONS = ("create", "decrypt", "edit", "encrypt", "rekey", "view") VALID_ACTIONS = ("create", "decrypt", "edit", "encrypt", "rekey", "view")
CIPHER = 'AES256'
def __init__(self, args, display=None):
def __init__(self, display=None):
self.vault_pass = None self.vault_pass = None
super(VaultCli, self).__init__(args, display)
if display is None:
self.display = Display()
else:
self.display = display
def parse(self): def parse(self):
# create parser for CLI options # create parser for CLI options
parser = base_parser( self.parser = CLI.base_parser(
usage = "%prog vaultfile.yml", usage = "%prog vaultfile.yml",
) )
return parser.parse_args() self.set_action()
# options specific to self.actions
if self.action == "create":
self.parser.set_usage("usage: %prog create [options] file_name")
elif self.action == "decrypt":
self.parser.set_usage("usage: %prog decrypt [options] file_name")
elif self.action == "edit":
self.parser.set_usage("usage: %prog edit [options] file_name")
elif self.action == "view":
self.parser.set_usage("usage: %prog view [options] file_name")
elif self.action == "encrypt":
self.parser.set_usage("usage: %prog encrypt [options] file_name")
elif action == "rekey":
self.parser.set_usage("usage: %prog rekey [options] file_name")
def run(self, options, args): self.options, self.args = self.parser.parse_args()
action = self.get_action(args) if len(self.args) == 0 or len(self.args) > 1:
self.parser.print_help()
raise AnsibleError("Vault requires a single filename as a parameter")
if not action: def run(self):
parser.print_help()
raise AnsibleError("missing required action")
# options specific to actions if self.options.vault_password_file:
if action == "create": # read vault_pass from a file
parser.set_usage("usage: %prog create [options] file_name") self.vault_pass = read_vault_file(self.options.vault_password_file)
elif action == "decrypt": elif self.options.ask_vault_pass:
parser.set_usage("usage: %prog decrypt [options] file_name") self.vault_pass, _= self.ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False)
elif action == "edit":
parser.set_usage("usage: %prog edit [options] file_name")
elif action == "view":
parser.set_usage("usage: %prog view [options] file_name")
elif action == "encrypt":
parser.set_usage("usage: %prog encrypt [options] file_name")
elif action == "rekey":
parser.set_usage("usage: %prog rekey [options] file_name")
if len(args) == 0 or len(args) > 1: self.execute()
parser.print_help()
raise AnsibleError("Vault requires a single filename as a parameter")
if options.vault_password_file: def execute_create(self):
# read vault_pass from a file
self.vault_pass = read_vault_file(options.vault_password_file)
else:
self.vault_pass, _= ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False)
# execute the desired action
fn = getattr(self, "execute_%s" % action)
fn(args, options)
def get_action(self, args):
"""
Get the action the user wants to execute from the
sys argv list.
"""
for i in range(0,len(args)):
arg = args[i]
if arg in VALID_ACTIONS:
del args[i]
return arg
return None
def execute_create(args, options):
cipher = 'AES256'
if hasattr(options, 'cipher'):
cipher = options.cipher
this_editor = VaultEditor(cipher, self.vault_pass, args[0])
this_editor.create_file()
def execute_decrypt(args, options): cipher = getattr(self.options, 'cipher', self.CIPHER)
this_editor = VaultEditor(cipher, self.vault_pass, self.args[0])
this_editor.create_file()
cipher = 'AES256' def execute_decrypt(self):
if hasattr(options, 'cipher'):
cipher = options.cipher
for f in args: cipher = getattr(self.options, 'cipher', self.CIPHER)
for f in self.args:
this_editor = VaultEditor(cipher, self.vault_pass, f) this_editor = VaultEditor(cipher, self.vault_pass, f)
this_editor.decrypt_file() this_editor.decrypt_file()
self.display.display("Decryption successful") self.display.display("Decryption successful")
def execute_edit(args, options): def execute_edit(self):
cipher = None
for f in args: for f in self.args:
this_editor = VaultEditor(cipher, self.vault_pass, f) this_editor = VaultEditor(None, self.vault_pass, f)
this_editor.edit_file() this_editor.edit_file()
def execute_view(args, options): def execute_view(self):
cipher = None
for f in args: for f in self.args:
this_editor = VaultEditor(cipher, self.vault_pass, f) this_editor = VaultEditor(None, self.vault_pass, f)
this_editor.view_file() this_editor.view_file()
def execute_encrypt(args, options): def execute_encrypt(self):
cipher = 'AES256' cipher = getattr(self.options, 'cipher', self.CIPHER)
if hasattr(options, 'cipher'): for f in self.args:
cipher = options.cipher
for f in args:
this_editor = VaultEditor(cipher, self.vault_pass, f) this_editor = VaultEditor(cipher, self.vault_pass, f)
this_editor.encrypt_file() this_editor.encrypt_file()
self.display.display("Encryption successful") self.display.display("Encryption successful")
def execute_rekey(args, options ): def execute_rekey(self):
__, new_password = ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=True, confirm_new=True) __, new_password = self.ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=True, confirm_new=True)
cipher = None for f in self.args:
for f in args: this_editor = VaultEditor(None, self.vault_pass, f)
this_editor = VaultEditor(cipher, self.vault_pass, f)
this_editor.rekey_file(new_password) this_editor.rekey_file(new_password)
self.display.display("Rekey successful") self.display.display("Rekey successful")
...@@ -179,15 +138,17 @@ class Cli(object): ...@@ -179,15 +138,17 @@ class Cli(object):
if __name__ == "__main__": if __name__ == "__main__":
display = Display() display = Display()
#display.display(" ".join(sys.argv), log_only=True)
try: try:
cli = Cli(display=display) cli = VaultCli(sys.argv, display=display)
(options, args) = cli.parse() cli.parse()
sys.exit(cli.run(options, args)) sys.exit(cli.run())
except AnsibleError as e: except AnsibleOptionsError as e:
display.display("[ERROR]: %s" % e, color='red', stderr=True) cli.parser.print_help()
display.display(str(e), stderr=True, color='red')
sys.exit(1) sys.exit(1)
except AnsibleError as e:
display.display(str(e), stderr=True, color='red')
sys.exit(2)
except KeyboardInterrupt: except KeyboardInterrupt:
display.display("[ERROR]: interrupted", color='red', stderr=True) display.error("interrupted")
sys.exit(1) sys.exit(4)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment