问题描述
我需要运行一个交互式脚本,才能使用Ansible剧本在我的服务器上安装应用程序客户端。在安装过程中,它会询问IP地址,端口号,服务器名称,用户名和密码。
- name: Install application client
hosts: all
tasks: Run the script
- name: Execute the user interactive script
command: /home/ansible/install.sh
在提示您输入答案之前
Enter IP: **1.2.3.4**
Enter Port: **440**
Enter Server Name: **AppServerName**
Connectivity Succeeded
Enter Username: **UserName**
Enter Password: **xxxx**
我想知道我们如何在剧本本身中预定义这些响应,并在提示时选择它?
谢谢, 让·托马斯(Jean Thomas)
解决方法
将此添加为答案。在您要运行的Shell脚本“期望”某些响应时,我们需要使用Linux expect
提供这些响应。
假设我们有一个简单的shell脚本test.sh
,如下所示。它需要IP地址和端口,然后运行nc
命令:
#!/bin/bash
echo "IP address:"
read ip_addr
echo "Port:"
read port
nc -vz $ip_addr $port
要使用expect
从Ansible运行此脚本,那么我们将有一个简单的剧本,如下所示:
- hosts: localhost
vars:
send_ip_addr: "1.2.3.4"
send_port: "22"
tasks:
- shell: |
spawn ./test.sh
expect "IP address:"
send -- "{{ send_ip_addr }}\n"
expect "Port:"
send -- "{{ send_port }}\n"
expect eof
args:
executable: /usr/bin/expect
Linux expect
本身就是一种脚本语言,而我们上面的内容是Ansible .exp
任务中的简单shell
脚本。我认为我们仅可以在开始时设置timeout
。有关所有受支持的选项,请参见manpage。
还有一个有用的autoexpect
命令将为我们创建一个script.exp
脚本。示例:
autoexpect test.sh