本文整理匯總了Python中ansible.playbook.play.Play方法的典型用法代碼示例。如果您正苦於以下問題:Python play.Play方法的具體用法?Python play.Play怎麽用?Python play.Play使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ansible.playbook.play
的用法示例。
在下文中一共展示了play.Play方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _execute_play
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def _execute_play(play_source, inventory, var_mgr, loader, options, callback): # pylint: disable=too-many-arguments
"""
Execute the playbook
"""
play = Play().load(play_source, variable_manager=var_mgr, loader=loader)
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=var_mgr,
loader=loader,
options=options,
passwords=None,
stdout_callback=callback,
)
_ = tqm.run(play)
except Exception as exc:
raise TaskExecutionException(str(exc))
finally:
if tqm is not None:
tqm.cleanup()
示例2: __init__
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def __init__(self, host_list, module_name, args, private_key_file="/root/.ssh/id_rsa", forks=5, extra_vars=None):
super(AnsibleAdhcTask, self).__init__(host_list, private_key_file, forks, extra_vars)
self.call_back = result_collector.CallbackModule()
# create inventory and pass to var manager
inventory = Inventory(loader=self.loader,
variable_manager=self.variable_manager,
host_list=host_list)
self.variable_manager.set_inventory(inventory)
# create play with tasks
play_source = dict(
name="Ansible Play",
hosts='all',
gather_facts='no',
tasks=[dict(action=dict(module=module_name, args=args))]
)
self.play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
示例3: setup
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def setup(self, pb_name="Dynamic playbook",
pb_tasks=None):
if not pb_tasks or not isinstance(pb_tasks, list):
raise CoPilotPlaybookError("Dynamic Playbook created with "
"missing/invalid tasks")
# define the playbook
play_src = dict(
name=pb_name,
hosts='all',
gather_facts="no",
tasks=pb_tasks
)
self.playbook = Play().load(play_src,
variable_manager=self.variable_manager,
loader=self.loader)
示例4: AnsibleExecApi29
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def AnsibleExecApi29(task_id, tasks=[], inventory_data=None):
options = get_default_options()
context.CLIARGS = ImmutableDict(options)
loader = DataLoader()
passwords = dict(vault_pass='secret')
results_callback = RedisCallBack(task_id)
# inventory = InventoryManager(loader=loader, sources='localhost,')
if inventory_data:
inventory = BaseInventory(inventory_data)
else:
inventory = BaseInventory(InventoryInit().get_data())
variable_manager = VariableManager(loader=loader, inventory=inventory)
play_source = dict(
name="Ansible Play",
hosts='localhost',
gather_facts='no',
tasks=tasks,
)
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
tqm = None
try:
tqm = MyTaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
passwords=passwords,
stdout_callback=results_callback,
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
# Ansible 2.9 版本的 vars/manager.py: VariableManager 未有 extra_vars.setter
示例5: run
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
for arg in self._task.args:
if arg not in self.VALID_ARGS:
result = {"failed": True, "msg": "{0} is not a valid option.".format(arg)}
return result
result = super(ActionModule, self).run(tmp, task_vars)
playbook_id = self._task.args.get("playbook_id", None)
if playbook_id is None:
# Retrieve the playbook id by working our way up from the task to find
# the play uuid. Once we have the play uuid, we can find the playbook.
parent = self._task
while not isinstance(parent._parent._play, Play):
parent = parent._parent
play = self.client.get("/api/v1/plays?uuid=%s" % parent._parent._play._uuid)
playbook_id = play["results"][0]["playbook"]
result["playbook"] = self.client.get("/api/v1/playbooks/%s" % playbook_id)
result["changed"] = False
result["msg"] = "Queried playbook %s from ARA" % playbook_id
return result
示例6: import_task
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def import_task(self, play_source):
super(EZSetupPlaybook, self).import_task(play_source)
# self.play.append(
# Play().load(
# play_source,
# variable_manager=self.variable_manager,
# loader=self.loader
# )
# )
# print(self.play)
示例7: run_adhoc
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run_adhoc(self, hosts, module_name, module_args=''):
###########################
# run module from andible ad-hoc.
##########################
play_source = dict(
name="Ansible Play",
hosts=hosts,
gather_facts='no',
tasks=[dict(action=dict(module=module_name, args=module_args))]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
# actually run it
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.callback,
)
tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
示例8: run_model
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run_model(self, host_list, module_name, module_args):
"""
run module from andible ad-hoc.
module_name: ansible module_name
module_args: ansible module args
"""
play_source = dict(
name="Ansible Play",
hosts=host_list,
gather_facts='no',
tasks=[dict(action=dict(module=module_name, args=module_args))]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
tqm = None
# if self.redisKey:self.callback = ModelResultsCollectorToSave(self.redisKey,self.logId)
# else:self.callback = ModelResultsCollector()
self.callback = ModelResultsCollector()
import traceback
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback = "minimal",
)
tqm._stdout_callback = self.callback
constants.HOST_KEY_CHECKING = False #關閉第一次使用ansible連接客戶端是輸入命令
tqm.run(play)
except Exception as err:
print traceback.print_exc()
# DsRedis.OpsAnsibleModel.lpush(self.redisKey,data=err)
# if self.logId:AnsibleSaveResult.Model.insert(self.logId, err)
finally:
if tqm is not None:
tqm.cleanup()
示例9: run
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run(self, tasks, pattern, play_name='Ansible Ad-hoc', gather_facts='no'):
"""
:param tasks: [{'action': {'module': 'shell', 'args': 'ls'}, ...}, ]
:param pattern: all, *, or others
:param play_name: The play name
:param gather_facts:
:return:
"""
self.check_pattern(pattern)
cleaned_tasks = self.clean_tasks(tasks)
play_source = dict(
name=play_name,
hosts=pattern,
gather_facts=gather_facts,
tasks=cleaned_tasks
)
play = Play().load(
play_source,
variable_manager=self.variable_manager,
loader=self.loader,
)
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
stdout_callback=self.results_callback,
passwords=self.options.passwords,
)
msg = ("Get matched hosts: {}".format(
self.inventory.get_matched_hosts(pattern)
))
try:
tqm.send_callback('on_playbook_start', play.name)
self.results_callback.display(msg)
tqm.run(play)
return self.results_callback.results
except Exception as e:
raise AnsibleError(e)
finally:
tqm.send_callback('v2_playbook_on_stats', tqm._stats)
tqm.send_callback('on_playbook_end', play.name)
tqm.cleanup()
self.loader.cleanup_all_tmp_files()
示例10: execute_action
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def execute_action(self, action, args):
"""
Execute the requested operation
"""
C.DEFAULT_ROLES_PATH = [os.path.join(ROLESDIR, str(action))]
i3xfce.loggers.ROOTLOGGER.debug("Executing the %s action", action)
# Get the real user behind the sudo
username = os.getenv("SUDO_USER")
if username is None:
i3xfce.loggers.ROOTLOGGER.debug("Unable to get SUDO_USER environment variable. This means i3-xfce has not been \
started using sudo")
raise Exception("This program must be ran using sudo ")
i3xfce.loggers.ROOTLOGGER.debug("Creating the option tuple")
options_tuple = namedtuple('Options', ['connection', 'forks', 'module_path', 'become_user', 'become',
'become_method', 'check', 'verbosity'])
try:
# initialize needed objects
variable_manager = VariableManager()
variable_manager.extra_vars = dict(action=str(action),
remote_user=username)
loader = DataLoader()
i3xfce.loggers.ROOTLOGGER.debug("Creating option to count number of tasks to execute")
options = options_tuple(connection=None, module_path=None, forks=1, become_user=None,
become=None, become_method=None, verbosity=0, check=True)
tasks_count_callback = TaskCountCallback()
# create inventory and pass to var manager
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=None)
variable_manager.set_inventory(inventory)
# create play with tasks
play_source = dict(
name="Ansible Play",
hosts='localhost',
gather_facts='no',
ignore_errors="yes",
roles=args.parts
)
CmdLine._execute_play(play_source, inventory, variable_manager, loader, options, tasks_count_callback)
i3xfce.loggers.ROOTLOGGER.debug("%i tasks are going to be executed", tasks_count_callback.get_total_tasks_num())
play_source["ignore_errors"] = "no"
options = options_tuple(connection=None, module_path=None, forks=1, become_user=None, become=None,
become_method=None, verbosity=0, check=args.dryrun)
self._results_callback = PlaybookExecutionCallback(tasks_count_callback.get_total_tasks_num(),
tasks_count_callback.get_task_name_max_len())
CmdLine._execute_play(play_source, inventory, variable_manager, loader, options, self._results_callback)
self._results_callback.get_progress_bar().stop()
self._results_callback.get_progress_bar().join()
if self._results_callback.get_task_failed() is True:
raise TaskExecutionException("")
except TaskExecutionException as exc:
raise
except Exception as exc:
raise TaskExecutionException(str(exc))
示例11: run
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run(self, inventory_content, pattern='all'):
'''
運行adhoc
'''
self.pattern = pattern
self.inventory_content = inventory_content
if not self.options.module_name :
self.logger.error(self.log_prefix + '準備工作失敗,原因:執行模塊不能為空')
return (False, '執行模塊不能為空,請輸入模塊名')
else:
if self.options.module_name in C.MODULE_REQUIRE_ARGS and not self.options.module_args :
self.logger.error(self.log_prefix + '準備工作失敗,原因:執行模塊參數為空')
return (False, '執行模塊參數為空,請輸入模塊參數')
for name, obj in get_all_plugin_loaders():
name = name
if obj.subdir:
plugin_path = os.path.join('.', obj.subdir)
if os.path.isdir(plugin_path):
obj.add_directory(plugin_path)
self._gen_tasks()
play = Play().load(self.tasks_dict, variable_manager=self.variable_manager, loader=self.loader)
try :
self.host_list = self.inventory.list_hosts(self.pattern)
except :
self.host_list = []
if len(self.host_list) == 0 :
self.logger.error(self.log_prefix + '準備工作失敗,原因:沒有匹配主機名')
return (False, '執行失敗,沒有匹配主機名')
self._loading_callback()
self._tqm = None
try:
self._tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.callback,
# run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS,
# run_tree=False,
)
self._tqm.run(play)
finally:
if self._tqm:
self._tqm.cleanup()
if self.loader:
self.loader.cleanup_all_tmp_files()
self.logger.info(self.log_prefix + '發送成功')
return True
示例12: run_module
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run_module(self, module_name='ping', module_args=None, hosts="all",
inventory_file=None, **kwargs):
if not module_args:
check_raw = module_name in ('command', 'win_command', 'shell',
'win_shell', 'script', 'raw')
module_args = parse_kv(constants.DEFAULT_MODULE_ARGS, check_raw)
conn_pass = None
if 'conn_pass' in kwargs:
conn_pass = kwargs['conn_pass']
become_pass = None
if 'become_pass' in kwargs:
become_pass = kwargs['become_pass']
passwords = {'conn_pass': conn_pass, 'become_pass': become_pass}
options = self._build_opt_dict(inventory_file, **kwargs)
variable_manager = vars.VariableManager()
loader = dataloader.DataLoader()
variable_manager.extra_vars = options.extra_vars
ansible_inv = inventory.Inventory(loader=loader,
variable_manager=variable_manager,
host_list=options.inventory)
variable_manager.set_inventory(ansible_inv)
ansible_inv.subset(options.subset)
play_ds = self._play_ds(hosts, module_name, module_args)
play_obj = play.Play().load(play_ds, variable_manager=variable_manager,
loader=loader)
try:
tqm = task_queue_manager.TaskQueueManager(
inventory=ansible_inv,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback='minimal',
run_additional_callbacks=True
)
# There is no public API for adding callbacks, hence we use a
# private property to add callbacks
tqm._callback_plugins.extend(self._callbacks)
result = tqm.run(play_obj)
finally:
if tqm:
tqm.cleanup()
if loader:
loader.cleanup_all_tmp_files()
stats = tqm._stats
result = self._process_stats(stats)
return result
示例13: run
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run(
self,
tasks,
pattern,
play_name='Ansible Ad-hoc',
gather_facts='no',):
"""
:param gather_facts:
:param tasks: [{'action': {'module': 'shell', 'args': 'ls'}, ...}, ]
:param pattern: all, *, or others
:param play_name: The play name
:return:
"""
self.check_pattern(pattern)
results_callback = self.results_callback_class()
cleaned_tasks = self.clean_tasks(tasks)
play_source = dict(
name=play_name,
hosts=pattern,
gather_facts=gather_facts,
tasks=cleaned_tasks
)
play = Play().load(
play_source,
variable_manager=self.variable_manager,
loader=self.loader,
)
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
stdout_callback=results_callback,
passwords=self.options.passwords,
)
try:
tqm.run(play)
return results_callback
except Exception as e:
raise AnsibleError(e)
finally:
tqm.cleanup()
self.loader.cleanup_all_tmp_files()
示例14: run
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
for arg in self._task.args:
if arg not in self.VALID_ARGS:
result = {"failed": True, "msg": "{0} is not a valid option.".format(arg)}
return result
result = super(ActionModule, self).run(tmp, task_vars)
playbook_id = self._task.args.get("playbook_id", None)
key = self._task.args.get("key", None)
value = self._task.args.get("value", None)
type = self._task.args.get("type", "text")
required = ["key", "value"]
for parameter in required:
if not self._task.args.get(parameter):
result["failed"] = True
result["msg"] = "Parameter '{0}' is required".format(parameter)
return result
if type not in self.VALID_TYPES:
result["failed"] = True
msg = "Type '{0}' is not supported, choose one of: {1}".format(type, ", ".join(self.VALID_TYPES))
result["msg"] = msg
return result
if playbook_id is None:
# Retrieve the playbook id by working our way up from the task to find
# the play uuid. Once we have the play uuid, we can find the playbook.
parent = self._task
while not isinstance(parent._parent._play, Play):
parent = parent._parent
play = self.client.get("/api/v1/plays?uuid=%s" % parent._parent._play._uuid)
playbook_id = play["results"][0]["playbook"]
try:
data, changed = self.create_or_update_key(playbook_id, key, value, type)
result["changed"] = changed
result["key"] = data["key"]
result["value"] = data["value"]
result["type"] = data["type"]
result["playbook_id"] = data["playbook"]
result["created"] = data["created"]
result["updated"] = data["updated"]
if result["changed"]:
result["msg"] = "Record created or updated in ARA"
else:
result["msg"] = "Record unchanged in ARA"
except Exception as e:
result["changed"] = False
result["failed"] = True
result["msg"] = "Record failed to be created or updated in ARA: {0}".format(str(e))
return result
示例15: __init__
# 需要導入模塊: from ansible.playbook import play [as 別名]
# 或者: from ansible.playbook.play import Play [as 別名]
def __init__(self, **kwargs):
super(Ansible_playbook, self).__init__(**kwargs)
self.task_file = kwargs.get('task_file', None)
self.sudo = kwargs.get('sudo', False)
self.sudo_user = kwargs.get('sudo_user', False)
self.sudo_password = kwargs.get('sudo_password', False)
# check if parameters have been provided
if self._is_parameters_ok():
# since the API is constructed for CLI it expects certain options to always be set in the context object
context.CLIARGS = self._get_options()
# initialize needed objects
loader = DataLoader()
passwords = {'become_pass': self.sudo_password}
inventory = InventoryManager(loader=loader, sources="localhost,")
# variable manager takes care of merging all the different sources to give you a unified
# view of variables available in each context
variable_manager = VariableManager(loader=loader, inventory=inventory)
variable_manager.set_inventory(inventory)
playbooks = None
with open(self.task_file, 'r') as stream:
try:
playbooks = yaml.full_load(stream)
except yaml.YAMLError as exc:
logger.debug("Ansibe playbook error: {}".format(exc))
if playbooks is not None:
# force usage of python 3 interpreter
playbooks[0].setdefault("vars", {})
playbooks[0]["vars"]["ansible_python_interpreter"] = "/usr/bin/python3"
play = Play().load(playbooks[0], variable_manager=variable_manager, loader=loader)
# Run it - instantiate task queue manager, which takes care of forking and setting up all objects
# to iterate over host list and tasks
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
passwords=passwords,
stdout_callback='default',
# Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
)
tqm.run(play) # most interesting data for a play is actually sent to the callback's methods
finally:
# we always need to cleanup child procs and the structres we use to communicate with them
if tqm is not None:
tqm.cleanup()