Ansible提供两种方式去完成任务,一是 ad-Hoc 命令,一是写 Ansible playbook.前者用于临时解决一些简单的任务, 后者用于计划性解决较复杂的任务.(ad-Hoc 命令和 ansible playbook 的关系类似于在命令行敲入shell命令和 写shell scripts两者之间的关系)。
1、Ansible命令语法:
ansible <host-pattern> [-f forks] [-m module_name] [-a args]
-f forks:启动的并发线程数;
-m module_name: 要使用的模块;
-a args: 模块特有的参数;
# 以指定用户名运行
ansible all -a "/usr/bin/foo" -u username
# 以sudo 运行
ansible all -a "/usr/bin/foo" -u username --sudo [--ask-sudo-pass]
2、常用命令模块
ping模块
ansible all -m ping
获取远程系统信息
ansible all -m setup
service 模块
ansible web -m service -a 'name=httpd state=started enabled=yes'
command: 命令模块,默认就是执行这个,可以省略command
ansible 192.168.1.101 -m command -a 'date'
shell:用到管道复杂命令功能时建议用shell
ansible all -m shell -a 'echo 123..com | passwd --stdin user1'
script:在远程主机执行脚本
ansible all -m script -a "/tmp/a.sh"
yum:安装程序包 卸载: state=absent 更新:stat=latest
ansible all -m yum -a "name=nginx state=present"
file: 更改文件的属主、group、创建目录,软连接
ansible all -m file -a 'owner=mysql group=mysql mode=644 path=/tmp/fstab.ansible' ansible all -m file -a ' path=/tmp/test mode=644' ansible all -m file -a 'src= /file/to/link/to dest:=/path/to/symlink state=link'
copy:复制本地文件到远程主机上
src=: 定义本地源文件路径
dest=: 定义远程目标文件路径
src=: 定义本地源文件路径
dest=: 定义远程目标文件路径
ansible all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ansible owner=root mode=640'
user: 创建用户, 删除用户后面跟上 state=absent
ansible all -m user -a “name = foo password = <crypted password here>”
cron模块: 让被管理节点生成定期自动运维计划
# 让2台主机每10分钟运行一次echo hell
# 让2台主机每10分钟运行一次echo hell
ansible webservs -m cron -a 'minute="*/10" job="/bin/echo hell" name="test cron job"'
git 模块: 使用 git 部署 webapp
ansible webservers -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"