Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible user-interactive module while running shell script

Tags:

ansible

I am new to ansible and trying to learn basic things...

I am trying to execute a below shell script with ansible...This script has case condition included which needs a user input. But while running in ansible, it's not asking anything and completing a task. I want my ansible to ask a i/p during executing and accordingly execute the script.

- hosts: localhost
  tasks:
  - name: Execute the script
    shell: /usr/bin/sh /root/ansible_testing/testing.sh

snippet of shell script is...

 echo "Press 1 for Backup"
 echo "Press 2 for MakeChange"
 echo "Press 3 for Keepsafe"
 echo "*******************************************"

 echo -n "Enter your choice : "
 read choice2

 case $choice2 in
 1)

   echo "Hello"
like image 355
BHY Avatar asked Aug 05 '17 20:08

BHY


People also ask

How do you call an shell script from Ansible?

Though Ansible Shell module can be used to execute Shell scripts. Ansible has a dedicated module named Script which can be used to copy the Shell script from the control machine to the remote server and to execute. Based on your requirement you can use either Script or Shell module to execute your scripts.

How do you run a shell script on a remote server using Ansible?

To run a command on a remote host we can use the Ansible's shell module (or win_shell for Windows targets). By default, the shell module uses the /bin/sh shell to execute commands, but it is possible to use other shells such as /bin/bash by passing the executable argument.

What is the difference between shell and command module in Ansible?

Both modules execute commands on target nodes but in a sensible different way. The command modules execute commands on the target machine without using the target shell, it simply executes the command. The target shell is for example the popular bash , zsh , or sh .

How do you use the shell module in Ansible playbook?

Ansible's shell module executes shell commands on remote hosts. By default, the shell module uses the /bin/sh shell to execute commands, but it's possible to use other shells such as /bin/bash by passing the executable argument.


1 Answers

There's a bunch of ways you can do this with just bash (there's a pretty good answer here). However if you want to accomplish this the Ansible way you could use the expect module.

- name: Execute the script
  expect:
    command: /usr/bin/sh /root/ansible_testing/testing.sh
    responses:
      "Enter your choice": "1"

In this example, Enter your choice is the regex ansible will match on to input a "1". If there are multiple prompts that use Enter your choice Ansible will input a "1" for all of them.

like image 177
kfreezy Avatar answered Sep 20 '22 00:09

kfreezy