Reputation: 23
I'm writing python script to run ansible playbook, using Ansible 2.4.2.0.
As I know there is an option --limit
, which can limit the Ansible play on a specific host.
For example:
Here is the /etc/ansible/hosts
[test]
192.168.0.1
192.168.0.2
Below command will let Ansible only execute test.yml on 192.168.0.1
:
ansible-playbook test.yml --limit="192.168.0.1"
I want to know how to set options in ansible playbook api to do the same thing.
I tried add to limit='192.168.0.1
in options, but it doesn't work.
Below is the Python script I used.
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()
Upvotes: 2
Views: 2397
Reputation: 68269
Ansible is opensourced, so you can always peek into the existing code.
It's here in ansible-playbook
CLI code:
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")
Source: Ansible's code source
So, your case, after your instantiation of InventoryManager
, you should add:
inventory.subset('192.168.0.1')
Upvotes: 2