使用shell模块,在远程命令通过/bin/sh来执行;所以,我们在终端输入的各种命令方式,都可以使用;
但是我们自己定义在.bashrc/.bash_profile中的环境变量shell模块由于没有加载,所以无法识别;如果需要使用自定义的环境变量,就需要在最开始,执行加载自定义脚本的语句;
对shell模块的使用可以分成两块:
shell模块用法和command参数一样
[[email protected] ~]# ansible-doc -s shell less 436 Copyright (C) 1984-2009 Mark Nudelman less comes with NO WARRANTY, to the extent permitted by law. For information about the terms of redistribution, see the file named README in the less distribution. Homepage: http://www.greenwoodsoftware.com/less - name: Execute commands in nodes. action: shell chdir # cd into this directory before running the command creates # a filename, when it already exists, this step will *not* be run. executable # change the shell used to execute the command. Should be an absolute path to the executable. free_form= # The shell module takes a free form command to run, as a string. There‘s not an actual option named "free form". See the examples! removes # a filename, when it does not exist, this step will *not* be run. warn # if command warnings are on in ansible.cfg, do not warn about this particular line if set to no/false.
如果待执行的语句少,写在一起也可以,还可以加载环境...... [[email protected] ~]# ansible web -m shell -a ‘. ~/.bash_profile;ps -ef|grep httpd‘ web | SUCCESS | rc=0 >> root 4406 4405 0 06:32 pts/0 00:00:00 /bin/sh -c . ~/.bash_profile;ps -ef|grep httpd root 4410 4406 0 06:32 pts/0 00:00:00 grep httpd
scripts模块可以在本地写一个脚本,然后在远程服务器上执行。如下
script用法
[[email protected] ~]# ansible-doc -s script less 436 Copyright (C) 1984-2009 Mark Nudelman less comes with NO WARRANTY, to the extent permitted by law. For information about the terms of redistribution, see the file named README in the less distribution. Homepage: http://www.greenwoodsoftware.com/less - name: Runs a local script on a remote node after transferring it action: script creates # a filename, when it already exists, this step will *not* be run. free_form= # path to the local script file followed by optional arguments. removes # a filename, when it does not exist, this step will *not* be run.
name: 将本地脚本复制到远程主机并运行之
action: script
creates # 一个文件名,当这个文件存在,则该命令不执行
free_form= # 本地脚本路径
removes # 一个文件名,这个文件不存在,则该命令不执行
[[email protected] ~]# cat time.sh #!/bin/bash date > /tmp/shijian
使用script模块执行,使用是相当路径也可以使用绝对路径。
[[email protected] ~]# ansible web -m script -a ‘time.sh‘ web | SUCCESS => { "changed": true, "rc": 0, "stderr": "", "stdout": "", "stdout_lines": [] }
验证下web服务器上内容
[[email protected] ~]# ansible web -a ‘cat /tmp/shijian‘
web | SUCCESS | rc=0 >>
Sun May 1 06:35:30 CST 2016
时间: 2024-10-07 03:51:24