安装 Ansible
Ansible 能够安装到 Linux、BSD、Mac OS X 等平台,Python 版本最低要求为 2.6。常用 Linux 发行一般可以通过其自带的包管理器安装 Ansible:
yum install ansible # RHEL/CentOS/Fedora,需要配置 EPEL
apt-get install ansible # Debian/Ubuntu
emerge -avt ansible # Gentoo/Funtoo
如果你在所用 Linux 发行版的包仓库中找不到 Ansible,那么也可以通过 pip 来安装 Ansible,同时也会安装 paramiko、PyYAML、jinja2 等 Python 依赖库。
pip install ansible
准备 Inventory
Inventory 文件用来定义你要管理的主机。其默认位置在 /etc/ansible/hosts ,如果不保存在默认位置,也可通过 -i 选项指定。被管理的机器可以通过其 IP 或域名指定。未分组的机器需保留在 hosts 的顶部,分组可以使用 [] 指定,如:
vim /etc/ansible/hosts
[cluster1]
192.168.0.1
192.168.0.2
192.168.0.3
[web]
linuxtoy.org
同时,分组也能嵌套:
[vps:children]
web
db
此外,也可以通过数字和字母模式来指定一系列连续主机,如:
[1:3].linuxtoy.org # 等价于
1.linuxtoy.org、2.linuxtoy.org、3.linuxtoy.org
[a:c].linuxtoy.org # 等价于
a.linuxtoy.org、b.linuxtoy.org、c.linuxtoy.org
还可以知道端口号、密码,如:
[port]
185.207.129.[26:35] ansible_ssh_pass=123456 ansible_ssh_port=80222
小试牛刀
[root@ydr1 ansible]# ansible -i hosts cluster1 -m ping -u root --ask-pass
SSH password:
192.168.0.1 | success >> {
"changed": false,
"ping": "pong"
}
192.168.0.2 | success >> {
"changed": false,
"ping": "pong"
}
192.168.0.3 | success >> {
"changed": false,
"ping": "pong"
}
该命令选项的作用分别为:
-i:指定 inventory 文件,使用当前目录下的 hosts
cluster1:针对 hosts 定义的所有主机执行,这里也可以指定组名或模式
-m:指定所用的模块,我们使用 Ansible 内置的 ping 模块来检查能否正常管理远端机器
-u:指定远端机器的用户
–ask-pass:由于机器之间没有配置ssh互信,所以采用密码登陆
执行命令
[root@ydr1 ansible]# ansible -i hosts cluster1 -a "echo hello" -u root --ask-pass
SSH password:
10.133.47.63 | success | rc=0 >>
hello
10.133.47.56 | success | rc=0 >>
hello
10.133.47.60 | success | rc=0 >>
hello
同步文件
[root@ydr1 ansible]# ansible -i hosts cluster1 -m copy -a 'src=/etc/hosts dest=/etc/hosts' -u root --ask-pass
SSH password:
10.133.47.63 | success >> {
"changed": false,
"dest": "/etc/hosts",
"gid": 0,
"group": "root",
"md5sum": "9a344ec9cbe4d95f61a341d89898ac25",
"mode": "0644",
"owner": "root",
"path": "/etc/hosts",
"size": 243,
"state": "file",
"uid": 0
}
10.133.47.56 | success >> {
"changed": true,
"dest": "/etc/hosts",
"gid": 0,
"group": "root",
"md5sum": "9a344ec9cbe4d95f61a341d89898ac25",
"mode": "0644",
"owner": "root",
"size": 243,
"src": "/root/.ansible/tmp/ansible-tmp-1462349801.87-21441601299854/source",
"state": "file",
"uid": 0
}
10.133.47.60 | success >> {
"changed": true,
"dest": "/etc/hosts",
"gid": 0,
"group": "root",
"md5sum": "9a344ec9cbe4d95f61a341d89898ac25",
"mode": "0644",
"owner": "root",
"size": 243,
"src": "/root/.ansible/tmp/ansible-tmp-1462349801.89-191102139612524/source",
"state": "file",
"uid": 0
}
其中-a参数表示模块参数
6.关于执行命令中需要使用到通配符
[root@ydr1 yum.repos.d]# ansible -i /etc/ansible/hosts remotehosts -a "rm -rf /etc/yum.repos.d/*" -u root --ask-pass
SSH password:
10.133.47.56 | success | rc=0 >>
10.133.47.60 | success | rc=0 >>
执行这样的命令是没有办法删除掉/etc/yum.repos.d/下的文件的。
使用raw 模块:
[root@ydr1 yum.repos.d]# ansible -i /etc/ansible/hosts remotehosts -m raw -a 'rm -rf /etc/yum.repos.d/*' -u root --ask-pass
SSH password:
10.133.47.60 | success | rc=0 >>
10.133.47.56 | success | rc=0 >>