Answering prompts from Ansible modules

In the module I’m developing I need to answer to a prompt while running a command using AnsibleModule.run_command. From what I have found so far, the most promising option is to use data parameter and send the answer to stdin of the command.

However, as far as I understand, it will only work in case if there is only one prompt. Consider the following bash script:

#!/usr/bin/env bash

read -p "Answer this (y/N) " ANSWER
read -p "Answer this #2 (y/N) " ANSWER2

RESULT=1
if [ "$ANSWER" == "y" ]
then
    echo "Answer #1 was: yes"
    RESULT=0
else
    echo "Answer #1 was: no"
    RESULT=1
fi
if [ "$ANSWER2" == "y" ]
then
    echo "Answer #2 was: yes"
    RESULT=0
else
    echo "Answer #2 was: no"
    RESULT=1
fi


exit $RESULT

In my module’s code I’m trying to execute this script, answering the script’s prompts:

def main():
    module = AnsibleModule(
        argument_spec=dict(
            script=dict(type='str', required=True)
        )
    )

    script = module.params['script']

    rc, stdout, stderr = module.run_command(script, data='y')

    if rc == 0:
        module.exit_json()
    else:
        module.fail_json(msg="Prompt was not answered correctly")

If there was only one prompt in the bash script, the module would finish successfully. But since there are more, only there first prompt gets its answer sent through data parameter.

Question
How to answer all prompts at once?

Maybe use expect through Python pexpect library?

1 Like

Wouldn’t it be better to just feed variables? So what used to be “prompts” in a Bash script would be variables in an ansible job?

ansible-playbook/playbook.yml -e '{"prompt1":"answer1","prompt2":"answer2"}'

Or feed it a variable file … this is what I do when I create a new server, I create a variable file with some variables defined (server name, subnet. etc.) - I do this for every server.

ansible-playbook/playbook.yml -e "@config/FILENAME.yml"

1 Like