Ansible主机清单文件用于定义要管理的主机及其相关信息。它是Ansible的核心配置文件之一,用于Ansible识别目标主机并与其建立连接。
主机清单文件通常位于Ansible控制器的/etc/ansible/hosts
目录下,也可自定义位置。文件内容使用YAML格式编写,语法简单易懂。
(host1做了免密登录 可以直接ssh访问)
(host2 没有免密登录 所以需要输入用户和密码才可以ssh访问)
这边host2访问失败也很正常因为没有设置免密需要用户和密码
访问的时候直接访问组 可以包括所有的主机 十分的方便
文件
/etc/ansible/hosts
是 Ansible 控制机上 Ansible 库存文件的默认位置。 有两种方法可以在此文件中定义主机:
[root@localhost ~]# ansible webServer -m ping -o
host2 | UNREACHABLE!: Failed to connect to the host via
ssh: ssh: Could not resolve hostname host2: Name or service not known
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python"
: "/usr/bin/python"}, "changed": false, "ping": "pong"}
我们在内部设置密码这样更加的方便快捷去访问
符合自动化运维的特征
接着我们在测试连通性(一举拿下!!!!!!!!!!!!)
ansible webServers -m ping -o
Ansible 组变量是一种将变量与主机组关联的方式,用于为组内所有主机设置共享属性。这可以简化 Playbook 的编写,提高配置的一致性和可维护性。
使用组变量具有以下优点:
vim /etc/ansible/host
通过以下配置就是创建一个webServers组 并且加入两个主机 再给组赋予变量 用户名和密码 这样组下的所有主机都可以访问 更加的便捷
[webServers]
host1
host2
[webServers:vars]
ansible_ssh_user='root'
ansible_ssh_pass='abc-123'
常用的一些变量
Ansible 中的子分组
Ansible 主机清单支持多级分组功能,也被称为子分组。这是一种将主机组织成层级结构的有效方法,可以使清单更易于管理和维护,尤其是在复杂的环境中。
使用子分组具有以下优点:
没有定义webServers组之前
调用的时候需要单独去输出
[root@localhost ~]# ansible apache -m ping -o
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
[root@localhost ~]# ansible mysql -m ping -u root -k -o
SSH password:
host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
定义之后
调用webServers就等于调用apache,mysql 并且给组赋予的属性(用户名和权限)也可以使用
[root@localhost ~]# ansible webServers -m ping -o
host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
Ansible 提供了多种方式来定义和管理主机列表,除了默认的 /etc/ansible/hosts
文件之外,您还可以使用自定义主机列表。这提供了更大的灵活性,允许您根据需要从不同来源获取主机信息。
使用自定义主机列表具有以下优点:
我们在当前的目录下定义一个hostlist 加入写好的配置衣语法
[root@localhost ~]# vim /etc/ansible/hosts
[root@localhost ~]# ls
anaconda-ks.cfg
[root@localhost ~]# ls
anaconda-ks.cfg
[root@localhost ~]# vim hostlist
[root@localhost ~]# ls
anaconda-ks.cfg hostlist
这时我们来测试一下
[root@localhost ~]# ansible -i hostlist webServers -m ping -o
host2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
host1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
ansible -i hostlist webServers -m ping -o
从hostlist中调用webServers这个组来检测
ansible
:这是 Ansible 可执行命令。-i hostlist
:此选项指定要使用的清单文件。在本例中,您使用的是名为 hostlist
的自定义清单文件。webServers
:这是您要在其上执行 Ansible 模块的目标主机组或主机名。-m ping
:此选项指定您要运行的 Ansible 模块。在这里,您使用 ping
模块来检查与目标主机的连接。