Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to override ansible.cfg variable from a subprocess.call from a python script?

When I run the following command from the command line
ANSIBLE_DISPLAY_OK_HOSTS=true ansible-playbook -i my_inventory.yaml myplaybook.yaml --tag my_tag
then everything works fine, however if I try to do so from a python script using subprocess.call, it fails with "No such file or directory: ‘ANSIBLE_DISPLAY_OK_HOSTS=true’

What is the difference and how to fix it please??

From within the python script I tried calling it by following ways:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1)
command = f"ANSIBLE_DISPLAY_OK_HOSTS=true ansible-playbook -i {inventory_path} {absolute_playbook_path} --tag {ansible_tag}" subprocess.run(command)

2)
command = ["ANSIBLE_DISPLAY_OK_HOSTS=true ansible-playbook", "-i", inventory_path, absolute_playbook_path, "--tag", ansible_tag] subprocess.run(command)

with no success.

>Solution :

You are trying to use shell syntax, but you’re not executing your command with a shell. Use the env keyword of subprocess.run to provide environment variables to your command:

env = {"ANSIBLE_DISPLAY_OK_HOSTS": "true"}
command = [
    "ansible-playbook",
    "-i", inventory_path,
    absolute_playbook_path,
    "--tag", ansible_tag
]
subprocess.run(command, env=env)

You could make version 1 of your command work by specifying shell=True, like this:

command = f"ANSIBLE_DISPLAY_OK_HOSTS=true ansible-playbook -i {inventory_path} {absolute_playbook_path} --tag {ansible_tag}" 
subprocess.run(command, shell=True)

But there’s really no reason to involve a shell in this invocation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading