管理配置Ansible
Ansible清单
定义清单
清单定义Ansible将要管理的一批主机。这些主机也可以分配到组中,以进行集中管理。组可以包含子组,主机也可以是多个组的成员。清单还可以设置应用到它所定义的主机和组的变量。
可以通过两种方式定义主机清单。静态主机清单可以通过文本文件定义。动态主机清单可以根据需要使用外部信息提供程序通过脚本或其他程序来生成。
清单的位置
/etc/ansible/hosts文件被视为系统的默认静态清单文件。不过,通常的做法是不使用该文件,而是在Ansible配置文件中为清单文件定义一个不同的位置。
[root@control ~]# cd /etc/ansible/
[root@control ansible]# touch inventory
[root@control ansible]# vim ansible.cfg
inventory = /etc/ansible/inventory #添加此行
使用静态清单指定受管主机
静态清单文件是指定Ansible目标受管主机的文本文件。可以使用多种不同的格式编写此文件,包括INI样式或YAML。
在最简单的形式中。INI样式的静态清单文件是受管主机的主机名或IP地址的列表,每行一个:
192.168.118.130
192.168.118.131
web1
web2
但通常而言,可以将受管主机组织为主机组。通过主机组,可以更加有效的对一系列系统运行Ansible。这时,每一部分的开头为以中括号括起来的主机组名称。其后为该组中每一受管主机的主机名或IP地址,每行一个。
web1
[webservers]
192.168.118.130
192.168.118.131
[dbservers]
web2
验证清单
若有疑问,可使用 ansible 命令验证计算机是否存在于清单中:
ansible [主机名/IP] --list-hosts
[root@control ~]# ansible web1 --list-hosts
hosts (1):
web1
运行以下命令来列出指定组中的所有主机:
ansible [组名称] --list-hosts
[root@control ~]# ansible webservers --list-hosts
hosts (2):
192.168.118.130
192.168.118.131
如果清单中含有名称相同的主机和主机组,ansible 命令将显示警告并以主机作为其目标。主机组则被忽略。
应对这种情况的方法有多种,其中最简单的是确保主机组不使用与清单中主机相同的名称。
构建Ansible清单
清单内容:
web1
[webservers]
192.168.118.130
192.168.118.131
[dbservers]
web2
使用以下命令列出默认清单文件中的所有受管主机:
ansible all --list-hosts
[root@control ~]# ansible all --list-hosts
hosts (4):
web1
192.168.118.130
192.168.118.131
web2
使用以下命令列出不属于任何组的受管主机:
ansible ungrouped --list-hosts
[root@control ~]# ansible ungrouped --list-hosts
hosts (1):
web1
使用以下命令列出属于某组的受管主机:
ansible dbservers --list-hosts
[root@control ~]# ansible dbservers --list-hosts
hosts (1):
web2
自定义清单文件
在清单的位置中已经创建一个名为inventory的自定义静态清单文件。
服务器清单规格
主机IP | 用途 | 位置 | 运行环境 |
---|---|---|---|
192.168.118.130 | web服务器 | 武汉 | 测试 |
192.168.118.131 | web服务器 | 武汉 | 生产 |
编辑/etc/ansible/inventory文件,将上表中所列出的主机加入受管主机序列。
[root@control ~]# vim /etc/ansible/inventory
[test]
192.168.118.130 ansible_user=root ansible_password=1
[produce]
192.168.118.131 ansible_user=root ansible_password=1
将密码写在配置文件里容易泄露,正确的做法是配置秘钥
[root@control ~]# ssh-keygen -t rsa #生成秘钥
[root@control ~]# ssh-copy-id root@192.168.118.130 #将秘钥传递给要被访问的主机
[root@control ~]# ssh-copy-id root@192.168.118.131
#配置文件就不需要写密码和用户名
[root@control ~]# vim /etc/ansible/inventory
[test]
192.168.118.130
[produce]
192.168.118.131
执行以下命令ping所有受管主机:
ansible all -m ping
[root@control ~]# ansible all -m ping
192.168.118.130 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
192.168.118.131 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
执行以下命令列出所有受管主机:
ansible all -i /etc/ansible/inventory --list-hosts
[root@control ~]# ansible all -i /etc/ansible/inventory --list-hosts
hosts (2):
1