我正在使用Ansible 2.4.2.0编写python脚本来运行ansible playbook 据我所知,有一个选项" - limit",它可以限制特定主机上的ansible游戏。
例如:
这是/ etc / ansible / hosts
[测试]
192.168.0.1
192.168.0.2
cmd下面只允许ansible在192.168.0.1上执行test.yml ansible-playbook test.yml --limit =" 192.168.0.1"
我想知道如何在ansible playbook api中设置选项来做同样的事情 我尝试添加" limit =' 192.168.0.1"在选项中,但它不起作用。
下面是我使用的python脚本。
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.executor.playbook_executor import PlaybookExecutor
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources=['/etc/ansible/hosts'])
variable_manager = VariableManager(loader=loader, inventory=inventory)
Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', 'connection','module_path', 'forks', 'remote_user', 'become', 'become_method', 'become_user', 'verbosity', 'check', 'diff', 'ask_sudo_pass', 'limit'])
options = Options(listtags=None, listtasks=None, listhosts=None, syntax=None, connection='smart', module_path=None, forks=100, remote_user=None, become=None, become_method='sudo', become_user='root', verbosity=None, check=False, diff=False, ask_sudo_pass=None, limit='192.168.0.1')
passwords = {}
pbex = PlaybookExecutor(playbooks=['/home/test.yml'], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)
pbex.run()
答案 0 :(得分:1)
Ansible是开源的,因此您可以随时查看现有代码。
它在ansible-playbook CLI中的here:
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")
在您的情况下:inventory.subset('192.168.0.1')