ansible与shell命令嵌套使用
实例1
利用ansible的shell模块查看proc_nodemanager进程。
ansible -i node-list all -m shell -a "for i in \`ps aux |grep proc_nodemanager | grep -v grep | awk '{print \$2}'\`; do echo \$i ; done" -k -u root
实例2:
ansible -i node-list all -m shell -a "ping -c 1 \`route -n | egrep '10.103.[0-9]+.1' | head -1 | awk '{print \$2}'\`" -k -u root
注:
注意其中转义字符"\"的使用.
egrep 命令不能识别“\d”这样的转义字符,所以用“[0-9]”代替。
实例3:
使用“file”模块,创建软连接,并修改属主和组,指定只运行在“example.phx.com”上:
ansible -i hosts/artemis all --limit=example.phx.com -m file -a "src='/etc/hdp/artemis-2.1.3.7-ha/hadoop/conf' dest=/apache/hive-0.13.0.2.1.3.7-21/conf owner=hadoop group=hadoop state=link force=yes" -u hcom -s
实例4
使用ansible的ping模块来查看主机列表是否存活和认证是否通过,
第一行命令是查看除dead外的所有其他主机;
第二行命令是查看dead里的所有主机。
ansible -i hosts/artemis all:\!dead -m ping -s -kK -f 200 --one-line > /dev/null
ansible -i hosts/artemis dead -m ping -s -kK -f 200 --one-line 2> /dev/null
实例5
第一行命令是运行在ares-dn组的前三行主机上;
第二行命令是运行在除dead外的ares-dn组的前三行主机上。
ansible -i ares-node-list ares-dn --limit=ares-dn[0-3] -m ping -u root -k --one-line
ansible -i ares-node-list ares-dn --limit=ares-dn[0-3]:\!dead -m ping -u root -k --one-line
实例6
在ansible命令中嵌套sed命令,下面这条命令是删除“hs-centos-updates”这段
ansible -i inventory_file PHX04-01-0160-0110 -m shell -a "sed \-i '/hs-centos-updates/,\$d' /etc/yum.repos.d/hs-centos.repo" -k -u root
实例7
以root用户登录后,再以hadoop用户来执行命令, 注意“-U hadoop”
ansible -i inventory_file PHX04-01-0160-0110 -m shell -a "bash /home/hadoop/bin/daemon_log_archive_hadoop.sh > /dev/null 2>&1" --one-line -k -u root -U hadoop -f 100