配置:
/etc/ansible/hosts文件的配置:
[app2]
10.0.0.236 ansible_ssh_user="root" ansible_ssh_pass="centos" ansible_ssh_port=22
10.0.0.234 ansible_ssh_user="root" ansible_ssh_pass="centos" ansible_ssh_port=22
118.89.168.180 ansible_ssh_user="root" ansible_ssh_pass="tsdsafsa" ansible_ssh_port=22
[app]
118.89.168.180
192.168.111.129
[webserver]
118.69.168.179
192.168.111.128
[dbserver]
118.69.168.178
192.168.111.18
ansible ad-hoc模式其实就是命令行模式:
command 模块
ansible app -m command -a "hostname"
ansible app -m command -a "whoami"
app是配置的所有的节点,-m后接模块信息
ping模块
ansible app -m ping
查看所有节点下的所有分支是否能被ping通
copy 模块:
ansible app -m copy -a "src=/root/1.sh dest=/tmp/data.txt"
ansible app -m file -a "dest=/tmp/data.txt mode=500 owner=root group=root" -become
-become就相当于是sudo
执行安装操作:
#在红帽或者是centos下的是yum安装
ansible app -m yum -a "name=git state=present" -become
present是创建任务,absent是删除任务
ad-hoc只是批量执行简单的任务。
inventory简单介绍
注:inventory为可管理的服务器集合的名称
1)默认情况下读取的是/etc/ansible/hosts文件
2)当然你可以通过 -i指定你想读取的hosts
ansible app -i /home/hosts --list-hosts #列出节点下的所有的服务器的集合。
3)你可以通过修改/etc/ansible/ansible.cfg文件中的inventory选项,该方法是实际中最长用的方法。
cat /etc/ansible/ansible.cfg
[defaults]
remote_port=20
remote_user = root
inventory = /home/wy/hosts
ansible dbserver --list-hosts #列出的所有的dbserver下的所有的服务器的ip
ansible '*' --list-hosts 列出所有的服务器的名字
ansible all --list-hosts 列出所有的服务器的名字
骚操作:##children的方式后只能跟组名
[common:children]
webserver
dbserver
当我们用common这个组去匹配的时候会匹配到webserver与dbserver组中的所有的服务器的名字。
那么我们有一批相同模式的服务器组咋办呢,答案是正则匹配或者切片匹配
[webservers]
web[1:3]server
ansible webservers -list–hosts
显示如下:
hosts (3)
web1.example.com
web2.example.com
web3.example.com
ansible <parten_goes_here> -m <module_name> -a
ansible使用的是模式匹配而不是组名,组名与模式匹配都是确定哪些服务器执行操作
ansible webservers -m command -a “name=httpd state=restarted”
ansible web*.example.com -m service -a “name=httpd state=restarted”
[dbservers]
db[a:d].example.com
匹配规则:
192.168.0.1或者web.example.com, 匹配ip或者域名多个则用冒号(:)隔开
webservers 直接是组名
all或* 匹配全部
webservers:!dbservers 匹配在webservers中不在dbservers中的
webservers:&dbservers 匹配在webservers中也在dbservers中的
*.example.com或192.168.使用通配符匹配
webserver[0],webservers[1:]使用索引或者切片
~(web|db)..example 以~开头的表示正则匹配
变量:
/etc/ansible/hosts
127.0.0.1 mysql_port=3306
[test]
192.168.10.18 mysql_port = 3307
192.168.10.19 mysql_port = 3308
ansible -all -a “echo {{mysql_port}}”
3306
3307
3308
若是test下的端口相同可写作如下:
[test]
192.168.10.18
192.168.10.19
[test:vars]
mysql_port = 3308