本文整理汇总了Python中ansible.parsing.dataloader.DataLoader.set_vault_password方法的典型用法代码示例。如果您正苦于以下问题:Python DataLoader.set_vault_password方法的具体用法?Python DataLoader.set_vault_password怎么用?Python DataLoader.set_vault_password使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ansible.parsing.dataloader.DataLoader
的用法示例。
在下文中一共展示了DataLoader.set_vault_password方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestDataLoaderWithVault
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class TestDataLoaderWithVault(unittest.TestCase):
def setUp(self):
self._loader = DataLoader()
self._loader.set_vault_password('ansible')
def tearDown(self):
pass
@patch.multiple(DataLoader, path_exists=lambda s, x: True, is_file=lambda s, x: True)
def test_parse_from_vault_1_1_file(self):
vaulted_data = """$ANSIBLE_VAULT;1.1;AES256
33343734386261666161626433386662623039356366656637303939306563376130623138626165
6436333766346533353463636566313332623130383662340a393835656134633665333861393331
37666233346464636263636530626332623035633135363732623332313534306438393366323966
3135306561356164310a343937653834643433343734653137383339323330626437313562306630
3035
"""
if PY3:
builtins_name = 'builtins'
else:
builtins_name = '__builtin__'
with patch(builtins_name + '.open', mock_open(read_data=vaulted_data.encode('utf-8'))):
output = self._loader.load_from_file('dummy_vault.txt')
self.assertEqual(output, dict(foo='bar'))
示例2: Runner
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class Runner(object):
def __init__(self, playbook, display, hosts=None, options={}, passwords={}, vault_pass=None):
self.options = Options()
for k, v in options.iteritems():
setattr(self.options, k, v)
self.display = display
self.display.verbosity = self.options.verbosity
# executor has its own verbosity setting
playbook_executor.verbosity = self.options.verbosity
# gets data from YAML/JSON files
self.loader = DataLoader()
if vault_pass is not None:
self.loader.set_vault_password(vault_pass)
elif 'VAULT_PASS' in os.environ:
self.loader.set_vault_password(os.environ['VAULT_PASS'])
# all the variables from all the various places
self.variable_manager = VariableManager()
if self.options.python_interpreter is not None:
self.variable_manager.extra_vars = {
'ansible_python_interpreter': self.options.python_interpreter
}
# set inventory, using most of above objects
self.inventory = Inventory(
loader=self.loader, variable_manager=self.variable_manager,
host_list=hosts)
if len(self.inventory.list_hosts()) == 0:
self.display.error("Provided hosts list is empty.")
sys.exit(1)
self.inventory.subset(self.options.subset)
if len(self.inventory.list_hosts()) == 0:
self.display.error("Specified limit does not match any hosts.")
sys.exit(1)
self.variable_manager.set_inventory(self.inventory)
# setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)
def run(self):
# run playbook and get stats
self.pbex.run()
stats = self.pbex._tqm._stats
return stats
示例3: Runner
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class Runner(object):
def __init__(self, hostnames, playbook, private_key_file, run_data, become_pass=None,
verbosity=0, callback=None, subset_pattern=None):
self.hostnames = hostnames
self.playbook = os.path.join(playbooks_dir, playbook)
self.run_data = run_data
self.options = Options(subset=subset_pattern, private_key_file=private_key_file, verbosity=verbosity)
self.display = Display()
self.display.verbosity = verbosity
playbook_executor.verbosity = verbosity
passwords = {'become_pass': None}
# Gets data from YAML/JSON files
self.loader = DataLoader()
self.loader.set_vault_password(os.environ.get('VAULT_PASS'))
self.variable_manager = VariableManager()
self.variable_manager.extra_vars = self.run_data
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=self.hostnames)
self.variable_manager.set_inventory(self.inventory)
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[self.playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)
if callback:
self.pbex._tqm._stdout_callback = callback
def run(self):
self.pbex.run()
stats = self.pbex._tqm._stats
run_success = True
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
if t['unreachable'] > 0 or t['failures'] > 0:
run_success = False
return run_success
示例4: __init__
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
def __init__(self, inventory, ask_vault_pass, vault_password_files, vault_ids):
if vault_ids or len(vault_password_files) > 1:
raise NotImplementedError
from ansible.cli import CLI
super(Inventory20, self).__init__()
loader = DataLoader()
if ask_vault_pass:
self.vault_pass = CLI.ask_vault_passwords()
elif vault_password_files:
self.vault_pass = CLI.read_vault_password_file(vault_password_files[0], loader)
if self.vault_pass is not None:
loader.set_vault_password(self.vault_pass)
self.variable_manager = VariableManager()
try:
self.inventory = ansible.inventory.Inventory(loader=loader,
variable_manager=self.variable_manager,
host_list=inventory)
except ansible.errors.AnsibleError:
raise NoVaultSecretFound
self.variable_manager.set_inventory(self.inventory)
示例5: setup_inventory
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
def setup_inventory(ctx):
"""sets up the inventory object for use by other functions"""
loader = DataLoader()
variable_manager = VariableManager()
if ctx.obj['vault_password_command']:
try:
vault_password = subprocess.check_output(ctx.obj['vault_password_command'], shell=True)
except subprocess.CalledProcessError:
print "Vault password command exited with non-zero code"
sys.exit(1)
loader.set_vault_password(vault_password.rstrip())
elif os.environ.get('ANSIBLE_VAULT_PASSWORD_FILE'):
with open(os.environ.get('ANSIBLE_VAULT_PASSWORD_FILE'), 'r') as vault_password_file:
loader.set_vault_password(vault_password_file.read().strip())
try:
if(ctx.obj['inventory']):
return Inventory(loader=loader,
variable_manager=variable_manager,
host_list=ctx.obj['inventory'])
else:
return Inventory(loader=loader,
variable_manager=variable_manager)
except AnsibleError as e:
# If it fails to decrypt and a password command hasn't been provided, prompt for one
if not ctx.obj['vault_password_command'] and str(e) == 'Decryption failed':
vault_password = getpass.getpass('Enter vault password:')
loader.set_vault_password(vault_password)
if(ctx.obj['inventory']):
return Inventory(loader=loader,
variable_manager=variable_manager,
host_list=ctx.obj['inventory'])
else:
return Inventory(loader=loader,
variable_manager=variable_manager)
else:
print "Something went wrong:"
print repr(e)
sys.exit(1)
示例6: run_command
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
def run_command(self, name, ctx=None):
cmd = self.able_file.get_command(name)
from able.ablefile.command import AbleCommand
if not isinstance(cmd, AbleCommand):
return 0
cmd.ablefile = self.able_file
params, global_params = utils.filter_params(ctx.params)
self.options = self.get_global_option_values(cmd, global_params)
if 'verbosity' in self.options:
display.verbosity = self.options.verbosity
# Note: slightly wrong, this is written so that implicit localhost
# Manage passwords
sshpass = None
becomepass = None
vault_pass = None
passwords = {}
# don't deal with privilege escalation or passwords when we don't need to
if not self.options.listhosts and not self.options.listtasks and not self.options.listtags and not self.options.syntax:
self.normalize_become_options()
(conn_pass, become_pass) = self.ask_passwords()
passwords['conn_pass'] = conn_pass if conn_pass is not None else self.options.conn_pass
passwords['become_pass'] = become_pass if become_pass is not None else self.options.become_pass
loader = DataLoader()
if self.options.vault_password_file:
# read vault_pass from a file
vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=loader)
loader.set_vault_password(vault_pass)
elif self.options.ask_vault_pass:
vault_pass = self.ask_vault_passwords()[0]
loader.set_vault_password(vault_pass)
variable_manager = cmd.get_variable_manager()
variable_manager.extra_vars = cmd.get_extra_vars(params, self.options)
loader = cmd.get_loader()
# create inventory and pass to var manager
inventory = AbleInventory(
loader=loader,
variable_manager=variable_manager,
host_list=cmd.get_inventory(),
inventory_files=cmd.get_inventory_files()
)
variable_manager.set_inventory(inventory)
# Run any confirmation prompts
cmd.do_confirm(variable_manager, loader)
# create the playbook executor, which manages running the plays via a task queue manager
ex = AbleCommandExecutor(
command=cmd,
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=self.options,
passwords=passwords)
results = ex.run()
if isinstance(results, list):
for p in results:
display.display('\nCommand: %s' % p['command'])
for idx, play in enumerate(p['plays']):
msg = "\n command #%d (%s): %s" % (idx + 1, ','.join(play.hosts), play.name)
mytags = set(play.tags)
msg += '\tTAGS: [%s]' % (','.join(mytags))
if self.options.listhosts:
playhosts = set(inventory.get_hosts(play.hosts))
msg += "\n pattern: %s\n hosts (%d):" % (play.hosts, len(playhosts))
for host in playhosts:
msg += "\n %s" % host
display.display(msg)
all_tags = set()
if self.options.listtags or self.options.listtasks:
taskmsg = ''
if self.options.listtasks:
taskmsg = ' tasks:\n'
all_vars = cmd.get_variable_manager().get_vars(loader=cmd.get_loader(), play=self)
play_context = PlayContext(play=self, options=self.options)
for block in play.compile():
block = block.filter_tagged_tasks(play_context, all_vars)
if not block.has_tasks():
continue
for task in block.block:
if task.action == 'meta':
continue
all_tags.update(task.tags)
if self.options.listtasks:
#.........这里部分代码省略.........
示例7: Runner
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class Runner(object):
def __init__(
self, playbook, display, hosts='hosts', options={}, passwords={},
vault_pass=None):
# Set options
self.options = Options()
for k, v in options.iteritems():
setattr(self.options, k, v)
# Set global verbosity
self.display = display
self.display.verbosity = self.options.verbosity
# Executor has its own verbosity setting
playbook_executor.verbosity = self.options.verbosity
# Gets data from YAML/JSON files
self.loader = DataLoader()
# Set vault password
if vault_pass is not None:
self.loader.set_vault_password(vault_pass)
elif 'VAULT_PASS' in os.environ:
self.loader.set_vault_password(os.environ['VAULT_PASS'])
# All the variables from all the various places
self.variable_manager = VariableManager()
if self.options.python_interpreter is not None:
self.variable_manager.extra_vars = {
'ansible_python_interpreter': self.options.python_interpreter
}
# Set inventory, using most of above objects
self.inventory = Inventory(
loader=self.loader, variable_manager=self.variable_manager,
host_list=hosts)
if len(self.inventory.list_hosts()) == 0:
# Empty inventory
self.display.error("Provided hosts list is empty.")
sys.exit(1)
self.inventory.subset(self.options.subset)
if len(self.inventory.list_hosts()) == 0:
# Invalid limit
self.display.error("Specified limit does not match any hosts.")
sys.exit(1)
self.variable_manager.set_inventory(self.inventory)
# import pdb; pdb.set_trace()
# Setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)
def run(self):
# Run Playbook and get stats
self.pbex.run()
stats = self.pbex._tqm._stats
# Test if success for record_logs
run_success = True
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
if t['unreachable'] > 0 or t['failures'] > 0:
run_success = False
# Dirty hack to send callback to save logs with data we want
# Note that function "record_logs" is one I created and put into
# the playbook callback file
# import pdb; pdb.set_trace()
self.pbex._tqm.send_callback('record_logs')
# os.remove(self.hosts.name)
return stats
示例8: run
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
def run(self):
super(PlaybookCLI, self).run()
# Note: slightly wrong, this is written so that implicit localhost
# Manage passwords
sshpass = None
becomepass = None
vault_pass = None
passwords = {}
# don't deal with privilege escalation or passwords when we don't need to
if not self.options.listhosts and not self.options.listtasks and not self.options.listtags and not self.options.syntax:
self.normalize_become_options()
(sshpass, becomepass) = self.ask_passwords()
passwords = { 'conn_pass': sshpass, 'become_pass': becomepass }
loader = DataLoader()
if self.options.vault_password_file:
# read vault_pass from a file
vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=loader)
loader.set_vault_password(vault_pass)
elif self.options.ask_vault_pass:
vault_pass = self.ask_vault_passwords()[0]
loader.set_vault_password(vault_pass)
# initial error check, to make sure all specified playbooks are accessible
# before we start running anything through the playbook executor
for playbook in self.args:
if not os.path.exists(playbook):
raise AnsibleError("the playbook: %s could not be found" % playbook)
if not (os.path.isfile(playbook) or stat.S_ISFIFO(os.stat(playbook).st_mode)):
raise AnsibleError("the playbook: %s does not appear to be a file" % playbook)
# create the variable manager, which will be shared throughout
# the code, ensuring a consistent view of global variables
variable_manager = VariableManager()
variable_manager.extra_vars = load_extra_vars(loader=loader, options=self.options)
variable_manager.options_vars = load_options_vars(self.options)
# create the inventory, and filter it based on the subset specified (if any)
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=self.options.inventory)
variable_manager.set_inventory(inventory)
# (which is not returned in list_hosts()) is taken into account for
# warning if inventory is empty. But it can't be taken into account for
# checking if limit doesn't match any hosts. Instead we don't worry about
# limit if only implicit localhost was in inventory to start with.
#
# Fix this when we rewrite inventory by making localhost a real host (and thus show up in list_hosts())
no_hosts = False
if len(inventory.list_hosts()) == 0:
# Empty inventory
display.warning("provided hosts list is empty, only localhost is available")
no_hosts = True
inventory.subset(self.options.subset)
if len(inventory.list_hosts()) == 0 and no_hosts is False:
# Invalid limit
raise AnsibleError("Specified --limit does not match any hosts")
# create the playbook executor, which manages running the plays via a task queue manager
pbex = PlaybookExecutor(playbooks=self.args, inventory=inventory, variable_manager=variable_manager, loader=loader, options=self.options, passwords=passwords)
results = pbex.run()
if isinstance(results, list):
for p in results:
display.display('\nplaybook: %s' % p['playbook'])
for idx, play in enumerate(p['plays']):
msg = "\n play #%d (%s): %s" % (idx + 1, ','.join(play.hosts), play.name)
mytags = set(play.tags)
msg += '\tTAGS: [%s]' % (','.join(mytags))
if self.options.listhosts:
playhosts = set(inventory.get_hosts(play.hosts))
msg += "\n pattern: %s\n hosts (%d):" % (play.hosts, len(playhosts))
for host in playhosts:
msg += "\n %s" % host
display.display(msg)
all_tags = set()
if self.options.listtags or self.options.listtasks:
taskmsg = ''
if self.options.listtasks:
taskmsg = ' tasks:\n'
def _process_block(b):
taskmsg = ''
for task in b.block:
if isinstance(task, Block):
taskmsg += _process_block(task)
else:
if task.action == 'meta':
continue
all_tags.update(task.tags)
#.........这里部分代码省略.........
示例9: parse_yaml_from_file
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
def parse_yaml_from_file(filepath):
dl = DataLoader()
if hasattr(dl, 'set_vault_password'):
dl.set_vault_password(DEFAULT_VAULT_PASSWORD)
return dl.load_from_file(filepath)
示例10: ConsoleCLI
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
#.........这里部分代码省略.........
for opt in oc['options'].keys():
display.display(' ' + stringc(opt, C.COLOR_HIGHLIGHT) + ' ' + oc['options'][opt]['description'][0])
else:
display.error('No documentation found for %s.' % module_name)
else:
display.error('%s is not a valid command, use ? to list all valid commands.' % module_name)
def complete_cd(self, text, line, begidx, endidx):
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
if self.options.cwd in ('all','*','\\'):
completions = self.hosts + self.groups
else:
completions = [x.name for x in self.inventory.list_hosts(self.options.cwd)]
return [to_native(s)[offs:] for s in completions if to_native(s).startswith(to_native(mline))]
def completedefault(self, text, line, begidx, endidx):
if line.split()[0] in self.modules:
mline = line.split(' ')[-1]
offs = len(mline) - len(text)
completions = self.module_args(line.split()[0])
return [s[offs:] + '=' for s in completions if s.startswith(mline)]
def module_args(self, module_name):
in_path = module_loader.find_plugin(module_name)
oc, a, _ = module_docs.get_docstring(in_path)
return oc['options'].keys()
def run(self):
super(ConsoleCLI, self).run()
sshpass = None
becomepass = None
vault_pass = None
# hosts
if len(self.args) != 1:
self.pattern = 'all'
else:
self.pattern = self.args[0]
self.options.cwd = self.pattern
# dynamically add modules as commands
self.modules = self.list_modules()
for module in self.modules:
setattr(self, 'do_' + module, lambda arg, module=module: self.default(module + ' ' + arg))
setattr(self, 'help_' + module, lambda module=module: self.helpdefault(module))
self.normalize_become_options()
(sshpass, becomepass) = self.ask_passwords()
self.passwords = { 'conn_pass': sshpass, 'become_pass': becomepass }
self.loader = DataLoader()
if self.options.vault_password_file:
# read vault_pass from a file
vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=self.loader)
self.loader.set_vault_password(vault_pass)
elif self.options.ask_vault_pass:
vault_pass = self.ask_vault_passwords()[0]
self.loader.set_vault_password(vault_pass)
self.variable_manager = VariableManager()
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=self.options.inventory)
self.variable_manager.set_inventory(self.inventory)
no_hosts = False
if len(self.inventory.list_hosts()) == 0:
# Empty inventory
no_hosts = True
display.warning("provided hosts list is empty, only localhost is available")
self.inventory.subset(self.options.subset)
hosts = self.inventory.list_hosts(self.pattern)
if len(hosts) == 0 and not no_hosts:
raise AnsibleError("Specified hosts and/or --limit does not match any hosts")
self.groups = self.inventory.list_groups()
self.hosts = [x.name for x in hosts]
# This hack is to work around readline issues on a mac:
# http://stackoverflow.com/a/7116997/541202
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
histfile = os.path.join(os.path.expanduser("~"), ".ansible-console_history")
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
self.set_prompt()
self.cmdloop()
示例11: Runner
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class Runner(object):
def __init__(self, groups, playbook, private_key_file, display, become_pass={}, extraVars={}):
self.extraVars = extraVars
self.options = Options()
self.options.private_key_file = private_key_file
self.options.verbosity = display.verbosity
self.options.connection = 'ssh' # Need a connection type 'smart' or 'ssh'
self.options.become = True
self.options.become_method = 'sudo'
self.options.become_user = 'root'
# Executor appears to have it's own
# verbosity object/setting as well
playbook_executor.verbosity = self.options.verbosity
# Become Pass Needed if not logging in as user root
passwords = {'become_pass':become_pass}
# Gets data from YAML/JSON files
self.loader = DataLoader()
self.loader.set_vault_password(os.environ.get('VAULT_PASS', 'xiaoy_pandan'))
# All the variables from all the various places
self.variable_manager = VariableManager()
self.variable_manager.extra_vars = self.extraVars
# Set inventory, using most of above objects
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=[])
self.variable_manager.set_inventory(self.inventory)
# Set groups info
for info in groups:
group = Group(info['name'])
self.inventory.add_group(group)
hostInfos = info.get('hosts')
for hostInfo in hostInfos:
hostname = hostInfo.get('hostname')
hostip = hostInfo.get('ip', hostname)
hostport = hostInfo.get('port')
username = hostInfo.get('username')
password = hostInfo.get('password')
ssh_key = hostInfo.get('ssh_key')
host = Host(name=hostname, port=hostport)
host.set_variable('ansible_ssh_host', hostip)
host.set_variable('ansible_ssh_port', hostport)
host.set_variable('ansible_ssh_user', username)
host.set_variable('ansible_ssh_pass', password)
host.set_variable('ansible_ssh_private_key_file', ssh_key)
for key, value in hostInfo.iteritems():
if key not in ['hostname', 'port', 'username', 'password', 'ssh_key']:
host.set_variable(key, value)
group.add_host(host)
varInfos = info.get('vars')
if varInfos:
for key, value in varInfos.iteritems():
group.set_variable(key, value)
# Playbook to run. Assumes it is
# local to this python file
pb_dir = os.path.dirname(__file__)
playbook = '%s/%s' % (pb_dir, playbook)
# Setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)
self.display = display
self.callback = CallbackModule(self.display)
self.pbex._tqm._stdout_callback = self.callback
def run(self):
# Results of PlaybookExecutor
self.pbex.run()
# calc result
result = True
hostResults = {}
stats = self.pbex._tqm._stats
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
if t['unreachable'] > 0 or t['failures'] > 0:
hostResult = result = False
else:
hostResult = True
hostResults[h] = hostResult
if result:
self.display.display('success')
else:
self.display.display('fail', stderr=True)
self.display.display('')
#.........这里部分代码省略.........
示例12: Runner
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class Runner(object):
def __init__(self, playbook, run_data, private_key_file=None, verbosity=0, host_file=None):
self.playbook = playbook
self.run_data = run_data
self.options = Options()
self.options.output_file = playbook + '.result'
self.options.private_key_file = private_key_file
self.options.verbosity = verbosity
self.options.connection = 'ssh' # Need a connection type "smart" or "ssh"
#self.options.become = True
self.options.become_method = 'sudo'
self.options.become_user = 'root'
# Set global verbosity
self.display = Display()
self.display.verbosity = self.options.verbosity
# Executor appears to have it's own
# verbosity object/setting as well
playbook_executor.verbosity = self.options.verbosity
# Become Pass Needed if not logging in as user root
#passwords = {'become_pass': become_pass}
# Gets data from YAML/JSON files
self.loader = DataLoader()
try:
self.loader.set_vault_password(os.environ['VAULT_PASS'])
except KeyError:
pass
# All the variables from all the various places
self.variable_manager = VariableManager()
self.variable_manager.extra_vars = {} # self.run_data
# Set inventory, using most of above objects
if (host_file):
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list = host_file)
else:
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager)
self.variable_manager.set_inventory(self.inventory)
# Setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords={})
def run(self):
os.environ['REQUESTS_CA_BUNDLE'] = '/usr/local/share/ca-certificates/local_certs.crt'
callback = ResultCallback()
self.pbex._tqm._stdout_callback = callback
self.pbex.run()
stats = self.pbex._tqm._stats
# Test if success for record_logs
run_success = True
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
if t['unreachable'] > 0 or t['failures'] > 0:
run_success = False
#os.remove(self.hosts.name)
return stats,callback.results
示例13: Runner
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class Runner(object):
def __init__(
self, playbook, options={}, passwords={},
vault_pass=None):
display = Display()
ansible_root = '/opt/emc'
pb_dir = "{0}/playbooks".format(ansible_root)
playbook = "{0}/{1}".format(pb_dir, playbook)
hosts = "{0}/hosts.ini".format(ansible_root)
# Set options
self.options = Options()
for k, v in options.iteritems():
setattr(self.options, k, v)
self.options.verbosity = 0
# Set global verbosity
self.display = display
self.display.verbosity = self.options.verbosity
# Executor has its own verbosity setting
playbook_executor.verbosity = self.options.verbosity
# Gets data from YAML/JSON files
self.loader = DataLoader()
# Set vault password
if vault_pass is not None:
self.loader.set_vault_password(vault_pass)
elif 'VAULT_PASS' in os.environ:
self.loader.set_vault_password(os.environ['VAULT_PASS'])
# All the variables from all the various places
self.variable_manager = VariableManager()
if self.options.python_interpreter is not None:
self.variable_manager.extra_vars = {
'ansible_python_interpreter': self.options.python_interpreter
}
# Set inventory, using most of above objects
self.inventory = Inventory(
loader=self.loader, variable_manager=self.variable_manager,
host_list=hosts)
if len(self.inventory.list_hosts()) == 0:
# Empty inventory
self.display.error("Provided hosts list is empty.")
sys.exit(1)
self.inventory.subset(self.options.subset)
if len(self.inventory.list_hosts()) == 0:
# Invalid limit
self.display.error("Specified limit does not match any hosts.")
sys.exit(1)
self.variable_manager.set_inventory(self.inventory)
# Setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)
def run(self):
# Run Playbook and get stats
self.pbex.run()
stats = self.pbex._tqm._stats
run_success = True
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
if t['unreachable'] > 0 or t['failures'] > 0:
run_success = False
# Do the callback
# self.pbex._tqm.send_callback(
# 'record_logs',
# success=run_success
# )
return run_success
示例14: InventoryCLI
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class InventoryCLI(CLI):
''' used to display or dump the configured inventory as Ansible sees it '''
ARGUMENTS = {'host': 'The name of a host to match in the inventory, relevant when using --list',
'group': 'The name of a group in the inventory, relevant when using --graph', }
def __init__(self, args):
super(InventoryCLI, self).__init__(args)
self.vm = None
self.loader = None
self.inventory = None
self._new_api = True
def parse(self):
self.parser = CLI.base_parser(
usage='usage: %prog [options] [host|group]',
epilog='Show Ansible inventory information, by default it uses the inventory script JSON format',
inventory_opts=True,
vault_opts=True
)
# Actions
action_group = optparse.OptionGroup(self.parser, "Actions", "One of following must be used on invocation, ONLY ONE!")
action_group.add_option("--list", action="store_true", default=False, dest='list', help='Output all hosts info, works as inventory script')
action_group.add_option("--host", action="store", default=None, dest='host', help='Output specific host info, works as inventory script')
action_group.add_option("--graph", action="store_true", default=False, dest='graph',
help='create inventory graph, if supplying pattern it must be a valid group name')
self.parser.add_option_group(action_group)
# Options
self.parser.add_option("-y", "--yaml", action="store_true", default=False, dest='yaml',
help='Use YAML format instead of default JSON, ignored for --graph')
self.parser.add_option("--vars", action="store_true", default=False, dest='show_vars',
help='Add vars to graph display, ignored unless used with --graph')
super(InventoryCLI, self).parse()
display.verbosity = self.options.verbosity
self.validate_conflicts(vault_opts=True)
# there can be only one! and, at least, one!
used = 0
for opt in (self.options.list, self.options.host, self.options.graph):
if opt:
used += 1
if used == 0:
raise AnsibleOptionsError("No action selected, at least one of --host, --graph or --list needs to be specified.")
elif used > 1:
raise AnsibleOptionsError("Conflicting options used, only one of --host, --graph or --list can be used at the same time.")
# set host pattern to default if not supplied
if len(self.args) > 0:
self.options.pattern = self.args[0]
else:
self.options.pattern = 'all'
def run(self):
results = None
super(InventoryCLI, self).run()
# Initialize needed objects
if getattr(self, '_play_prereqs', False):
self.loader, self.inventory, self.vm = self._play_prereqs(self.options)
else:
# fallback to pre 2.4 way of initialzing
from ansible.vars import VariableManager
from ansible.inventory import Inventory
self._new_api = False
self.loader = DataLoader()
self.vm = VariableManager()
# use vault if needed
if self.options.vault_password_file:
vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=self.loader)
elif self.options.ask_vault_pass:
vault_pass = self.ask_vault_passwords()
else:
vault_pass = None
if vault_pass:
self.loader.set_vault_password(vault_pass)
# actually get inventory and vars
self.inventory = Inventory(loader=self.loader, variable_manager=self.vm, host_list=self.options.inventory)
self.vm.set_inventory(self.inventory)
if self.options.host:
hosts = self.inventory.get_hosts(self.options.host)
if len(hosts) != 1:
raise AnsibleOptionsError("You must pass a single valid host to --hosts parameter")
myvars = self._get_host_variables(host=hosts[0])
self._remove_internal(myvars)
#.........这里部分代码省略.........
示例15: Runner
# 需要导入模块: from ansible.parsing.dataloader import DataLoader [as 别名]
# 或者: from ansible.parsing.dataloader.DataLoader import set_vault_password [as 别名]
class Runner(object):
def __init__(self,
hosts=None,
playbook=None,
remote_user='ubuntu',
private_key_file='~/.ssh/id_rsa',
become_pass='',
verbosity=0,
extra_vars={}):
"""
Arguments:
hosts:- The hosts. See the docstring of InventoryWrapper.__init__
for more details on the acceptable formats.
playbook:- is the path to the playbook file
become_pass:- seems like the password
for priviledge escalation
"""
if not hosts or not playbook:
raise ValueError("hosts and playbook arguments must be defined")
self.run_data = extra_vars
self.options = Options()
self.options.private_key_file = os.path.expanduser(private_key_file)
self.options.verbosity = verbosity
self.options.connection = 'ssh' # Need a connection type "smart" or "ssh"
self.options.become = True
self.options.become_method = 'sudo'
self.options.become_user = 'root'
self.options.remote_user = remote_user
# Set global verbosity
self.display = Display()
self.display.verbosity = self.options.verbosity
# Executor appears to have it's own
# verbosity object/setting as well
playbook_executor.verbosity = self.options.verbosity
# Become Pass Needed if not logging in as user root
passwords = {'become_pass': become_pass}
# Gets data from YAML/JSON files
self.loader = DataLoader()
self.loader.set_vault_password(os.environ['VAULT_PASS'])
# All the variables from all the various places
self.variable_manager = VariableManager()
self.variable_manager.extra_vars = self.run_data
# Parse hosts, I haven't found a good way to
# pass hosts in without using a parsed template :(
# (Maybe you know how?)
self.hosts = NamedTemporaryFile(delete=False, dir=os.getcwd())
self.inventory_wrapper = InventoryWrapper(hosts)
self.hosts.write(str(self.inventory_wrapper))
self.hosts.close()
# Set inventory, using most of above objects
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=self.hosts.name)
self.variable_manager.set_inventory(self.inventory)
# Setup playbook executor, but don't run until run() called
self.pbex = playbook_executor.PlaybookExecutor(
playbooks=[playbook],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=passwords)
def run(self):
# Results of PlaybookExecutor
self.pbex.run()
stats = self.pbex._tqm._stats
# Test if success for record_logs
run_success = True
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
if t['unreachable'] > 0 or t['failures'] > 0:
run_success = False
# Dirty hack to send callback to save logs with data we want
# Note that function "record_logs" is one I created and put into
# the playbook callback file
#FIXME: get rid of the following, since this is not being used
self.pbex._tqm.send_callback(
'record_logs',
user_id=None, #self.run_data['user_id'],
success=run_success
)
# Remove created temporary files
os.remove(self.hosts.name)
return stats