运行 shell 脚本时的 Ansible 用户交互模块

BHY*_*BHY 9 ansible

我是 ansible 的新手,正在尝试学习基本的东西......

我正在尝试使用 ansible 执行下面的 shell 脚本...该脚本包含需要用户输入的情况条件。但是在 ansible 中运行时,它不会询问任何内容并完成任务。我希望我的 ansible 在执行期间询问 ai/p 并相应地执行脚本。

- hosts: localhost
  tasks:
  - name: Execute the script
    shell: /usr/bin/sh /root/ansible_testing/testing.sh
Run Code Online (Sandbox Code Playgroud)

shell脚本的片段是...

 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"
Run Code Online (Sandbox Code Playgroud)

kfr*_*ezy 9

有很多方法可以只用 bash 来做到这一点(这里有一个很好的答案)。但是,如果您想以 Ansible 方式完成此操作,您可以使用Expect 模块

- name: Execute the script
  expect:
    command: /usr/bin/sh /root/ansible_testing/testing.sh
    responses:
      "Enter your choice": "1"
Run Code Online (Sandbox Code Playgroud)

在此示例中,Enter your choice正则表达式 ansible 将匹配输入“1”。如果有多个使用Enter your choiceAnsible 的提示,将为所有提示输入“1”。