配置环境
yum install wget -y
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
下载ansible
yum install ansible -y
安装与了解
查看版本与配置文件
# 查看版本
[root@server ~]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
# 查看配置文件所在位置
[root@server ~]# rpm -qc ansible
/etc/ansible/ansible.cfg
/etc/ansible/hosts
生成秘钥
[root@server ~]# ssh-keygen
[root@server ~]# cat /root/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDWhVpJQgu8npiXHLMb81w2ZseUFkADQslYpreoKw0n4bpWqE8iEtV6bYfIBoHb5sr1bMz945H9tzh+qmmuPMT9FLy/LBDXRcDvnZfRPLGyftrO+Zt/FMySxpmeQbcRMHggpIyiQePC4zo/6nrROSh1CRj/05KhYBbjNJSS9z9WnUSOfWa4CVzSRr67JFpgCTOxD1tsxzOLs1AhguUXrPGbgbLva5fW9IQO/kGBH6ZaLzWY1+diy6VP+B3gJx+w+Lllp1pqvO/mjGvqWG8Ib7MtP7M39UttkCutZmPC688v03VurufxuNPm/qlWwrShl0weO5VSl4gRvUHiVjFlhEXh root@server
# 复制到server_1到server_2里可以直接免密码登录
[root@server ~]# ssh-copy-id 192.168.100.30
[root@server ~]# ssh-copy-id 192.168.100.40
配置ansible
# 创建主机组(可以创建多个)
[root@server ~]# vim /etc/ansible/hosts
## db-[99:101]-node.example.com
[server]
192.168.100.30
192.168.100.40
# 远程链接模块(-m:使用模块 -f:使用交互式输入ssh的密码)
[root@server ~]# ansible -m ping 192.168.100.30
192.168.100.30 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
# 查看主机组里的主机内存使用情况
[root@server ~]# ansible -m shell -a "free -m" server
192.168.100.40 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 3773 125 3457 11 189 3412
Swap: 3071 0 3071
192.168.100.30 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 3773 125 3458 11 189 3413
Swap: 3071 0 3071
ansible命令参数
参数 功能
-i 指定hosts文件路径,默认在/etc/ansible/hosts
-m 指定使用的module名称,默认command模块
-a 指定模块参数
-k(小写) 提示输入ssh密码,并非基于ssh密钥认证
-K(大写) 提示输入sudo密码
-b 使用sudo执行命令
-become-user= 指定sudo的用户
-f,-forks=NUM NUM默认是整数5,指定fork开启同步进程的个数
-u 指定远程主机的执行用户
-v 详细模式,如果执行成功,输出详细结果,-vv -vvv更详细过程
-C 预执行检测
-T 执行命令的超时时间,默认10s
--list 显示主机列表,也可以用--list-hosts
--version 显示版本
ansible配置清单
构建清单
[root@server ~]# cd /etc/ansible/
[root@server ansible]# vim skk
server2
[test]
192.168.100.30
[demo]
192.168.100.40
# 查看 skk 清单中的主机
[root@server ansible]# ansible all -i skk --list-hosts
hosts (3):
server2
192.168.100.30
192.168.100.40
# 查看 skk 清单中未定义组的主机
[root@server ansible]# ansible ungrouped -i skk --list-hosts
hosts (1):
server2
# 查看 skk 清单中组为test的主机
[root@server ansible]# ansible test -i skk --list-hosts
hosts (1):
192.168.100.30
嵌套清单
[root@server ansible]# cat skk
server2
[test]
192.168.100.30
[demo]
192.168.100.40
[westos:children]
test
demo
[root@server ansible]# ansible westos -i skk --list-hosts
hosts (2):
192.168.100.30
192.168.100.40
主机范围化
[root@server ansible]# cat end