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

Time:01-26

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:

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.

CodePudding user response:

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.

  • Related