# use ansible api to push files to remote hosts

**URL:** <https://forum.ansible.com/t/use-ansible-api-to-push-files-to-remote-hosts/32176>\
**Category:** Ansible Developer\
**Created:** [February 7, 2020, 5:15pm UTC](https://forum.ansible.com/t/use-ansible-api-to-push-files-to-remote-hosts/32176 "2020-02-07T17:15:25Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mario\_Garcia](https://avatars.discourse-cdn.com/v4/letter/m/b782af/32.png) [@Mario\_Garcia](https://forum.ansible.com/u/Mario_Garcia)\
**Post date:** [February 7, 2020, 5:15pm UTC](https://forum.ansible.com/t/use-ansible-api-to-push-files-to-remote-hosts/32176/1 "2020-02-07T17:15:25Z")

</div>

Hello,

i am looking to create a tool that pushes sudoers file to remote file using the ansible api

it is a tool for some non technical users

this is what I have

`  
from ansible.parsing.dataloader import DataLoader  
from ansible.module\_utils.common.collections import ImmutableDict  
from ansible.inventory.manager import InventoryManager  
from ansible.cli import CLI  
from ansible.vars.manager import VariableManager  
from ansible.executor.playbook\_executor import PlaybookExecutor  
from ansible.playbook.play import Play  
from ansible import context

from sudo\_manager.objects import Host  
from sudo\_manager import render\_sudoers  
from sudo\_manager.objects import HostGroup

def get\_arguments():  
parser = argparse.ArgumentParser()  
group = parser.add\_mutually\_exclusive\_group(required=True)  
group.add\_argument(“–hostnames”, dest=‘hosts’, help=‘list of hosts seperated by comma or a file name (one hostname per line)’)  
group.add\_argument(“–hostgroup”, dest=‘hostgrp’, help=‘enter hostgroup name’)  
parser.add\_argument(“–dest\_dir”, dest=‘dest\_dir’, help='where to store the sudoers file, dafault is the current directory ', default=“.”)

return parser

def get\_hosts(hostgroup):  
hostgrp = HostGroup.get\_hostgroup(hostgroup)  
hosts = hostgrp.hosts  
output =   
for host in hosts:  
output.append(host.hostname)  
return output

arguments = get\_arguments().parse\_args()  
hostnames =

if arguments.hosts:  
hostnames = arguments.hosts.strip().split(‘,’)

hostnames = [x.strip() for x in list(hostnames)]  
hostnames = filter(None, hostnames)  
hostnames = set(hostnames)

if arguments.hostgrp:  
hostnames = get\_hosts(arguments.hostgrp)

for hostname in hostnames:  
sudoers\_content = render\_sudoers(hostname, ‘sudoers.j2’)  
_sudoers = os.path.join(arguments.dest\_dir, 'sudoers_%s’ % hostname)

with open(\_sudoers, ‘w’) as sudoers\_file:  
sudoers\_file.write(sudoers\_content)

my\_inv = ‘,’.join(hostnames)+ ‘,’  
print (my\_inv)

loader = DataLoader()

context.CLIARGS = ImmutableDict(tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False, connection=‘ssh’,  
module\_path=None, forks=100, private\_key\_file=None,  
ssh\_common\_args=None, ssh\_extra\_args=None, sftp\_extra\_args=None, scp\_extra\_args=None,  
verbosity=True, check=False, start\_at\_task=None)

Inventory = InventoryManager(loader=loader, sources=my\_inv)

variable\_manager = VariableManager(loader=loader, inventory=Inventory)

pbex = PlaybookExecutor(playbooks=[‘/usr/home/secops\_ansible/ansible/test.yml’], inventory=Inventory, variable\_manager=variable\_manager, loader=loader,passwords={})

results = pbex.run()  
`

the purpose of this is that user will call a script with a list of hosts or a hostgroup name…then our "sudo\_manager will get the hosts, generate the sudoers files… write them to disk and then ansible will push them to all the hosts that were passed as argument.

this is the test,yml contents:

`

- name: deploy sudoers files to remote hosts  
hosts: all  
become: yes

tasks:

- name: push files  
copy:  
src: “{{ playbook\_dir }}/sudoers\_{{ ansible\_nodename}}”  
dest: /etc/sudoers3x  
validate: /usr/sbin/visudo -cf %s

`

when i call the script with some debuging info like show os version it works…

but when i call it with the copy or template module i get an error like this:

> 

> an exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: expected string or buffer  
> fatal: [vm]: FAILED! =\> {“msg”: “Unexpected failure during module execution.”, “stdout”: “”}

thank you for your assistance.
