Ansible + Python2 implements batch execution of commands

Ansible 2.6 version api interface URL: https://docs.ansible.com/ansible/2.6/dev_guide/developing_api.html#python-api-example

Here you can find the API interface and example of ansible 2.6 version, and it can work according to the official example.

This article is ansible combined with python2.7

code show as below:

#!/usr/bin/env python
#!coding: utf8

import shutil
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
import ansible.constants as C

# Set ansible options by naming tuples and assigning values.
# Where connection is local, ssh, smart. Using smart will automatically apply local or ssh according to the actual situation. module_path is the path of the module. Just keep it. Forks is multi-process execution. Not too much. Just keep it.
Options = namedtuple ('Options', [' connection ',' module_path ',' forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
options = Options (connection = 'smart ', module_path = [' / to / mymodules'], forks = 10, become = None, become_method = None, become_user = None, check = False, diff = False)

# Use the DataLoader module, this module's role is to query and parse the provided files, such as yaml format, json format, ini format.
# passwords The purpose of this item is to do file encryption and decryption. Generally, it is unnecessary to use, so this dictionary is empty
loader = DataLoader ()
passwords = dict ()

# Use InventoryManager module to define inventory attribute, which is generally a string or a file. We are here to write the data of the host into the hosts file. Then here should be the path of the hosts file
inventory = InventoryManager (loader = loader, sources = '/ root / myansible / hosts')

# Use VariableManager module to manage variables
variable_manager = VariableManager (loader = loader, inventory = inventory)

# Create a play. The meanings of the fields inside are the name of the play, the effective host, whether to collect information, and the task.
play_source = dict (
        name = "Ansible Play",
        hosts = 'all',
        gather_facts = 'no',
        tasks = [
            dict (action = dict (module = 'shell', args = 'ls'), register = 'shell_out' ),
            dict (action = dict (module = 'debug', args = dict (msg = '{{shell_out}}'))))
         ]
    )

# Use the Play module, import parameters, and generate an instance
play = Play (). Load (play_source, variable_manager = variable_manager, loader = loader)

# Use TaskQueueManager module. Run the instance.
tqm = None
try:
    tqm = TaskQueueManager (
              inventory = inventory,
              variable_manager = variable_manager,
              loader = loader,
              options = options,
              passwords = passwords,
          )
    result = tqm.run (play) # return result
finally:
    # finally execute ansible anyway Cleanup. The working process of ansible is the first ssh connection,
    # Create a temporary directory on the target host. Disconnect. The second ssh connection, transfer ansible command file on the target host,
    # disconnect. The third ssh connection, modify the execution permissions of the command file, and disconnect. The fourth ssh connection, execute the command.
    # Obtain the returned json information, then delete the temporary directory and disconnect.
    if tqm is not None:
        tqm.cleanup ()

    # Finally, perform ansible cleanup anyway.
    shutil.rmtree (C.DEFAULT_LOCAL_TMP, True)

Published 73 original articles · praised 4 · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_27592485/article/details/102402650