bash 如何使用ansible运行需要中断操作的shell文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35052609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use ansible to run a shell file which needs an interrupt action
提问by Quoc Lap
I'm using ansible 1.9.4 to run a shell bash in server, and I have a trouble. For example, I have a jdk file named jdk-1_5_0_22-linux-amd64.binand I want to do something like the command below to install java:
我正在使用 ansible 1.9.4 在服务器中运行 shell bash,但遇到了麻烦。例如,我有一个名为jdk-1_5_0_22-linux-amd64.bin的 jdk 文件 ,我想执行以下命令来安装 java:
./jdk-1_5_0_22-linux-amd64.bin
But when I run this command, the screen shown me the License Agreement and asked me "Press space or Enter" to scroll that, then press "yes" to confirm.
但是当我运行这个命令时,屏幕向我显示了许可协议,并要求我“按空格键或 Enter”来滚动它,然后按“是”进行确认。
Or when I try to run a shell bash that includes something like:
或者当我尝试运行包含以下内容的 shell bash 时:
echo "restart ntp ?[y/n]"
read check
I have tried it in ansible by shell, script, commandmodules but it didn't run for me, ansible was paused. Look like ansible was waiting for my interrupt action. How can I do this? I can't find it anywhere in the documentation.
我已经通过shell、脚本、命令模块在 ansible 中尝试过它,但它没有为我运行,ansible 被暂停。看起来 ansible 正在等待我的中断操作。我怎样才能做到这一点?我在文档中的任何地方都找不到它。
回答by Michael
You can use either yes
(see: man yes
) or expect
. Whereas yes
continuously sends y answer to any process:
您可以使用yes
(请参阅:)man yes
或expect
. 而yes
不断地向任何进程发送 y 答案:
yes | install.sh
expect
will listenfor an expect output and then send a reply accordingly.
expect
将侦听预期输出,然后相应地发送回复。
(install expect
, apt-get install expect
, yes
should be a part of you linux distro already)
(安装expect
,apt-get install expect
,yes
应该是你的Linux发行版的一部分的话)
#!/usr/bin/expect
set timeout 10
spawn ./jdk-1_5_0_22-linux-amd64.bin
expect "Input your name:"
send "Quoc Lap\r"
interact
This little script will output your name if jdk install process ask for "input your name:"
. Note that the name string ends with a return character \r
如果 jdk 安装过程要求,这个小脚本会输出你的名字"input your name:"
。请注意,名称字符串以返回字符结尾\r
interact
will make sure to close and send the proper exit code.
interact
将确保关闭并发送正确的退出代码。
man expect
will provide you with examples and info on how to deal with more complicated flows.
man expect
将为您提供有关如何处理更复杂流程的示例和信息。
Finally
最后
You ansible playbook will then need to call the script above
然后你的 ansible playbook 需要调用上面的脚本
- name: Install Java JDK (automatic install)
shell: ./jdk_install.sh
args:
chdir=/path/to/your/script
If you don't need to run from a specific location just prepend the path to the shell action and remove the args-part.
如果您不需要从特定位置运行,只需将路径添加到 shell 操作并删除 args-part。