1.ad-hoc
- ansible.cfg文件打开ssh key check参数:
ansible test -m yum -a "name=bind state=present"
- 一般ansible远程连接机器执行命令时都是提前先将master与机器之间配置无密码登陆,但是其实hosts主机文件中也是可以设置携带密码进行远程主机操作的,如下:
[test]
192.168.1.4 ansible_ssh_pass=123456
- 远程执行命令
- ansible中存在一个名为ping的模块,该模块并不是测试服务器的网络是否连接,而是尝试建立ssh连接,以便验证用户的ssh是否已经正确配置。
- command是ansible的默认模块,当我们省略-m参数时,默认使用command模块
ansible test -m command -a "hostname"
ansible test -m ping
- 远程主机文件拷贝
ansible test -m copy -a "src=/tmp/sunwei dest=/etc/"
- 修改文件的所有者和权限
ansible test -m copy -a "src=/tmp/sunwei dest=/etc/"
- 远程主机安装&卸载软件
ansible test -m yum -a "name=bind state=present"
ansible test -m yum -a "name=bind state=absent"
- 服务的停止、启动、重启、重新加载
ansible all -m service -a "name=httpd state=started" #启动
ansible all -m service -a "name=httpd state=stopped" #停止
ansible all -m service -a "name=httpd state=restarted" #重启
ansible all -m service -a "name=httpd state=reloaded" #重新加载
2.ansible-playbook
将ad-hoc方式所编写的命令写入一个yaml文件中,使用ansible-playbllk执行文件被称为ansible-playbook
- 一个简单的小例子
cat playbook.yaml
---
- hosts: test
tasks:
#拷贝文件
- name: copy file
copy: src=/tmp/sunwei dest=/tmp/
#拷贝文件
- name: install softeare
#使用变量
yum: name={{item}} state=absent
with_items:
- bind
- httpd
#执行命令
ansible-playbool playbook.yaml
3.灵活定义hosts内容
下面举几个小例子,解释一般如何定义hosts文件内容
- 范例1 直接将ip或者主机名写入
cat /etc/asnible/hosts
192.168.1.1
192.168.1.2
test1.example.com
test2.example.com
执行ad-hoc命令时用法:
- ansible 192.168.1.* -m ping
- ansible * -m ping
- ansible all -m ping
- ansible test*.example.com
- 范例2 将主机进行分组
[webserver]
192.168.1.1
192.168.1.2
192.168.1.3
[dbserver]
192.168.1.4
192.168.1.5
192.168.1.6
执行ad-hoc命令时用法:
- ansible webserver -m ping
- ansible dbserver -m ping
- ansible all -m ping
- 远程服务器匹配规则如下表
规则 | 含义 |
---|---|
192.168.0.1或web.example.com | 匹配目标ip地址或者服务器主机名,如果有多个ip,使用:分隔 |
webserver | 匹配目标组为webserver,多个使用:分隔 |
*或者all | 匹配所有服务器 |
webserver:!dbserver | 匹配在webserver中,不在dbserver中 |
webserver:&dbserver | 同时匹配在webserver中和在dbserver中 |
.example.com或192.168.1. | 使用通配符进行匹配 |
webserver[0],webserver[1:] | 使用索引或者切片进行匹配 |
~(web竖线db).*.example.com | 以~开头的匹配,表示使用正则表达式匹配 |