ansible 快速入门

安装

$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible

配置文件

/etc/ansible/hosts  #主机分组
/etc/ansible/ansible.cfg  #ansible 配置文件

第一个命令

$ ansible all -m ping


-u 参数指定用户
$ ansible all -m ping -u bruce
# as bruce, sudoing to root
$ ansible all -m ping -u bruce --sudo
# as bruce, sudoing to batman
$ ansible all -m ping -u bruce --sudo --sudo-user batman

常用命令命令模块:

命令模块Commands:

每次重启10个主机
$ ansible atlanta -a "/sbin/reboot" -f 10

  

shell模块:

$ ansible raleigh -m shell -a 'echo $TERM'

  

文件模块File Transfer:

拷贝文件
$ ansible atlanta -m copy -a "src=/etc/hosts dest=/tmp/hosts"
更改文件属性
$ ansible webservers -m file -a "dest=/srv/foo/a.txt mode=600"
$ ansible webservers -m file -a "dest=/srv/foo/b.txt mode=600 owner=mdehaan group=mdehaan"
创建文件夹
$ ansible webservers -m file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory"
递归删除
$ ansible webservers -m file -a "dest=/path/to/c state=absent"

  

包模块Managing Packages:

支持yum和apt
确认一个包已经安装
$ ansible webservers -m yum -a "name=acme state=present"
确认一个包没有安装
$ ansible webservers -m yum -a "name=acme state=absent
确认一个软件包的安装版本
$ ansible webservers -m yum -a "name=acme-1.5 state=present"

Users and Groups:

$ ansible all -m user -a "name=foo password=<crypted password here>"

$ ansible all -m user -a "name=foo state=absent"

Deploying From Source Control:

直接使用 git 部署 webapp:

$ ansible webservers -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"

  

Managing Services:

确认某个服务在所有的webservers上都已经启动:
$ ansible webservers -m service -a "name=httpd state=started"
或是在所有的webservers上重启某个服务(译者注:可能是确认已重启的状态?):
$ ansible webservers -m service -a "name=httpd state=restarted"
确认某个服务已经停止:
$ ansible webservers -m service -a "name=httpd state=stopped"

  

Time Limited Background Operations:

需要长时间运行的命令可以放到后台去,在命令开始运行后我们也可以检查运行的状态.如果运行命令后,不想获取返回的信息, 可执行如下命令:

$ ansible all -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff"
如果你确定要在命令运行后检查运行的状态,可以使用 async_status 模块.前面执行后台命令后会返回一个 job id, 将这个 id 传给 async_status 模块:

$ ansible web1.example.com -m async_status -a "jid=488359678239.2844"
获取状态的命令如下:

$ ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"
其中 -B 1800 表示最多运行30分钟, -P 60 表示每隔60秒获取一次状态信息.

Polling 获取状态信息的操作会在后台工作任务启动之后开始.若你希望所有的工作任务快速启动, --forks 这个选项的值 要设置得足够大,这是前面讲过的并发进程的个数.在运行指定的时间(由``-B``选项所指定)后,远程节点上的任务进程便会被终止.

一般你只能在把需要长时间运行的命令或是软件升级这样的任务放到后台去执行.对于 copy 模块来说,即使按照前面的示例想放到 后台执行文件传输,实际上并不会如你所愿.

Gathering Facts:

在 playbooks 中有对于 Facts 做描述,它代表的是一个系统中已发现的变量.These can be used to implement conditional execution of tasks but also just to get ad-hoc information about your system. 可通过如下方式查看所有的 facts:

$ ansible all -m setup

  

  

 

原文地址:https://www.cnblogs.com/37yan/p/7112536.html