ansiblea基本使用

复制

copy模块

使用copy模块,可以将本地文件一键复制到远程服务器; 
-a后跟上参数,参数中指定本地文件和远端路径;

ansible myservers -m copy -a "src=/opt/app/bin/transfer.tar dest=~/"

ansible通过ssh登录到远程服务器后,并不执行.bash_profile来设置用户自定义的环境变量;如果我们需要管理的目标服务器的路径不同,就不能直接写绝对路径,也不能写变量替换的路径;

比如:针对服务器A的目标复制路径为 /opt/app/user1/bin ,服务器B的目标复制路径为/opt/app/user2/bin; 这两个路径在各自的服务器中的路径变量都设置为$bin; 但在copy模块中,我们不能直接使用dest = $bin/; 
路径设置一般放在.bashrc /.bash_profile文件,但ansible模块登录后并不加载这两个文件;

解决方法: 
针对这种情况,可以将dest路径设置为~/,都复制到用户目录,后续再通过远程脚本处理;

远程批量命令

需要在远程执行一个个命令来管理远程服务器;

远程执行命令的模块有command、shell、scripts、以及raw模块;

command模块

command模块为ansible默认模块,不指定-m参数时,使用的就是command模块; 
comand模块比较简单,常见的命令都可以使用,但其命令的执行不是通过shell执行的,所以,像这些 "<", ">", "|", and "&"操作都不可以,当然,也就不支持管道; 
示例:显示远程路径:

ansible myservers -a 'pwd'10.6.143.38| success | rc=0>>/home/rduser 10.6.143.53| success | rc=0>>/home/rduser 10.6.143.37| success | rc=0>>/home/rduser

缺点:不支持管道,就没法批量执行命令;

shell模块

使用shell模块,在远程命令通过/bin/sh来执行;所以,我们在终端输入的各种命令方式,都可以使用; 
但是我们自己定义在.bashrc/.bash_profile中的环境变量shell模块由于没有加载,所以无法识别;如果需要使用自定义的环境变量,就需要在最开始,执行加载自定义脚本的语句;

对shell模块的使用可以分成两块: 
1) 如果待执行的语句少,可以直接写在一句话中:

ansible myservers -a ". .bash_profile;ps -fe |grep sa_q"-m shell

2) 如果在远程待执行的语句比较多,可写成一个脚本,通过copy模块传到远端,然后再执行;但这样就又涉及到两次ansible调用;对于这种需求,ansible已经为我们考虑到了,script模块就是干这事的;

scripts模块

使用scripts模块可以在本地写一个脚本,在远程服务器上执行:

ansible myservers -m script -a "/opt/app/target.sh"

这里是命令模块的官方文档: 
http://docs.ansible.com/list_of_commands_modules.html

批量执行playbooks

远程批量命令执行的另外一种方式是用playbooks; 
这里是playbooks的官方文档:http://docs.ansible.com/playbooks.html 
这里有ansible的playbooks示例:https://github.com/ansible/ansible-examples

在python中使用ansbile API

以上执行ansible模块的方式都是在命令行中直接调用,如果对返回结果需要进一步处理,可以在程序中通过API调用的方式来使用ansible模块: 
比如,以上在命令行中调用scripts的模块的方式在API中调用:

import ansible.runner results = ansible.runner.Runner( pattern='myservers', forks=5, module_name='script', module_args='/opt/app/target.sh',).run()

这里是官方给出的一个详细示例,直接运行一次,将result全部打印出来,会有直观的了解:

#!/usr/bin/pythonimport ansible.runner import sys # construct the ansible runner and execute on all hosts results = ansible.runner.Runner( pattern='*', forks=10, module_name='command', module_args='/usr/bin/uptime',).run()if results isNone:print"No hosts found" sys.exit(1)print"UP ***********"for(hostname, result)in results['contacted'].items():ifnot'failed'in result:print"%s >>> %s"%(hostname, result['stdout'])print"FAILED *******"for(hostname, result)in results['contacted'].items():if'failed'in result:print"%s >>> %s"%(hostname, result['msg'])print"DOWN *********"for(hostname, result)in results['dark'].items():print"%s >>> %s"%(hostname, result)

API设计详见:http://docs.ansible.com/developing_api.html

 

转自:http://www.cnblogs.com/me115/archive/2015/05/27/4529944.html

你可能感兴趣的:(ansible,基本模块操作)