ansible主机清单和动态主机清单

inventory主机清单文件

主机清单的路径在/etc/ansible/ansible.cfg文件中的inventory参数定义
不修改,默认主机清单路径是 /etc/ansible/hosts

[student@workstation ~]$ cat /etc/ansible/ansible.cfg

[defaults]

# some basic default values...

#inventory      = /etc/ansible/hosts

在这里插入图片描述


编辑主机清单

在这里插入图片描述

vim /etc/ansible/hosts
## 添加主机组
[webservers]
192.168.0.11 ansible_ssh_user=root ansible_ssh_pass=123.com ansible_ssh_port=3333
192.168.0.12 ansible_ssh_user=root ansible_ssh_pass=123.com
## ansible_ssh_user=root  指定主机登陆用户名为root
## ansible_ssh_pass=123.com 指定主机登陆用户的密码为123.com
## ansible_ssh_port=3333  指定ssh的端口

# 保存主机清单并退出
:wq!

定义主机范围

适用于主机数量多和有规律的主机

[usa]
192.168.0.[0:254]
192.168.1.[0:254]
# 高级写法
192.168.[0:1].[0:254]

server[a:z]
server[1:254]

嵌套组写法

[student]  # 红帽294练习环境组
workstation.lab.example.com
server[a:d].lab.exmaple.com
astion.lab.example.com

[test]   # test组
node1
[proxy]		# proxy组
node2
[webserver]		# webserver组
node[3:4]
[database]		# 数据库组	
node5
# 定义嵌套组(主组套子组,子组用:chidren定义)
[cluster:children]		# 集群组
webserver      # webserver组
database		# database组

在这里插入图片描述


查看主机列表(inventory)中的主机信息

ansible -i 可以指定主机清单文件

# ansible -i 主机清单文件 主机组/主机名 --list-all
[student@workstation ~]$ ansible -i inventory all --list-hosts
  hosts (6):
    workstation.lab.example.com
    servera.lab.example.com
    serverb.lab.example.com
    serverc.lab.example.com
    serverd.lab.example.com
    astion.lab.example.com

主机清单内置参数

参考: https://blog.51cto.com/breezey/1757643
在这里插入图片描述

参数解释
ansible_ssh_host用于指定被管理的主机的真实IP
ansible_ssh_port用于指定连接到被管理主机的ssh端口号,默认是22
ansible_ssh_userssh连接时默认使用的用户名
ansible_ssh_passssh连接时的密码
ansible_sudo_pass使用sudo连接用户时的密码
ansible_sudo_exec如果sudo命令不在默认路径,需要指定sudo命令路径
ansible_ssh_private_key_file秘钥文件路径,秘钥文件如果不想使用ssh-agent管理时可以使用此选项
ansible_shell_type目标系统的shell的类型,默认sh
ansible_connectionSSH 连接的类型: local , ssh , paramiko,在 ansible 1.2 之前默认是 paramiko ,后来智能选择,优先使用基于 ControlPersist 的 ssh (支持的前提)
ansible_python_interpreter用来指定python解释器的路径,默认为/usr/bin/python 同样可以指定ruby 、perl 的路径
ansible_*_interpreter其他解释器路径,用法与ansible_python_interpreter类似,这里"*"可以是ruby或才perl等其他语言

主主机组指定密码变量

# 为所有主机组指定密码
[all:vars]
ansible_ssh_pass=rhel
# 
ansible_ssh_pass='rhel'

对主机组设置变量group_vras

# 在主机清单文件的同目录下新建目录group_vras
mkdir group_vras

# 如果要对all组生效变量,就创建一个all文件
touch all

# 将变量写入all文件中
## 例如,将ssh密码写在all文件中
ansible_ssh_pass: redhat

操作主机清单

ansible测试主机是否可达
https://blog.csdn.net/QYHuiiQ/article/details/119548059

# 查看所有主机是否可以连通
ansible all -m ping

# 查看webservers主机组的磁盘空间
ansible webservers -m shell -a "df -h"

## 绿色结果是执行成功
# 查看webservers主机组的内存使用情况
ansible webservers -m shell -a "free -h"

在这里插入图片描述

在这里插入图片描述


使用yaml主机清单


练习第二章练习:主机清单


开始新章节的环境

[student@workstation ~]$ lab deploy-inventory start

Setting up workstation for lab exercise work:

 · Verify ansible is installed on workstation control node.....  SUCCESS
 · Backup /etc/ansible/hosts inventory.........................  SUCCESS

编辑主机清单

在student的home目录下创建主机清单deploy_inventory

[student@workstation ~]$ touch ~/deploy_inventory

# 编辑主机清单内容
[student@workstation ~]$ vim deploy_inventory

写入的主机清单内容

workstation.lab.example.com
astion.lab.example.com

# 根据服务器角色分组
[webserver]
server[a:d].lab.example.com

# 根据服务器环境分组
[Development]
servera.lab.example.com

[Testing]
serverb.lab.example.com

[Production]
server[c:d].lab.example.com

# 根据地理位置分组
[Raleigh]
server[a:b].lab.example.com

[Mountaion_View]
serverc.lab.example.com

[London]
serverd.lab.example.com

查看主机清单

# 查看所有主机
[student@workstation ~]$ ansible all --list-hosts
  hosts (6):
    workstation.lab.example.com
    astion.lab.example.com
    servera.lab.example.com
    serverb.lab.example.com
    serverc.lab.example.com
    serverd.lab.example.com

# 查看不属于任何组的主机
[student@workstation ~]$ ansible ungrouped --list-hosts
  hosts (2):
    workstation.lab.example.com
    astion.lab.example.com

指定主机清单文件查看主机清单

ansible底层调用的是json格式的主机清单
编写主机清单的时候,必须要确认能解析成json

# 指定主机清单文件查看主机清单
[student@workstation files]$ ansible-inventory -i inventory --list
{
    "_meta": {
        "hostvars": {
            "servera.lab.example.com": {},
            "workstation.lab.example.com": {}
        }
    },
    "all": {
        "children": [
            "ungrouped",
            "webservers",
            "workstations"
        ]
    },
    "webservers": {
        "hosts": [
            "servera.lab.example.com"
        ]
    },
    "workstations": {
        "hosts": [
            "workstation.lab.example.com"
        ]
    }
}

动态主机清单文件

aws,阿里云等云服务器厂商,开放了相关的接口,是可以动态拉取主机清单的。
需要自己写python脚本动态生成主机清单。
厂商一般会提供demo。


动态主机清单示例1

新建python文件inventorya.py

#!/usr/bin/python3

from subprocess import Popen,PIPE
import sys
import json

result = {}
result['webservers'] = {}
result['webservers']['hosts'] = []
result['webservers']['vars'] = {}

pipe = Popen(['getent', 'hosts'], stdout=PIPE, universal_newlines=True)

for line in pipe.stdout.readlines():
   s = line.split()
   if s[1].startswith('servera'):
      result['webservers']['hosts'].append(s[1])

if len(sys.argv) == 2 and sys.argv[1] == '--list':
    print(json.dumps(result))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
    print(json.dumps({}))
else:
    print("Requires an argument, please use --list or --host <host>")

动态主机清单示例2

新建python文件inventoryw.py

#!/usr/bin/python3

from subprocess import Popen,PIPE
import sys
import json

result = {}
result['all'] = {}

pipe = Popen(['getent', 'hosts'], stdout=PIPE, universal_newlines=True)

result['all']['hosts'] = []
for line in pipe.stdout.readlines():
   s = line.split()
   if s[1].startswith('workstation'):
      result['all']['hosts'].append(s[1])

result['all']['vars'] = {}

if len(sys.argv) == 2 and sys.argv[1] == '--list':
    print(json.dumps(result))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
    print(json.dumps({}))
else:
    print("Requires an argument, please use --list or --host <host>")

查看动态主机清单文件的主机列表

# 赋予python脚本可执行权限
chmod +x inventory/inventorya.py

# 查看主机清单
[student@workstation ]$ ./inventory/inventorya.py --list
{"webservers": {"hosts": ["servera.lab.example.com"], "vars": {}}}

ansible指定动态主机清单文件

# 赋予python脚本可执行权限
chmod +x inventory/inventorya.py

# 指定动态主机清单文件查看主机列表
ansible -i inventory/inventorya.py webservers --list-host

完成练习

[student@workstation ~]$ lab deploy-inventory finish

Cleanup workstation control node

 · Restore /etc/ansible/hosts..................................  SUCCESS
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Ansible中,主机清单是一个文件,用于存储要管理的主机列表及其相关信息。主机清单文件可以是静态的,也可以是动态的。 静态主机清单的写法如下: ``` [web_servers] web1 ansible_host=192.168.1.101 ansible_user=root web2 ansible_host=192.168.1.102 ansible_user=root [db_servers] db1 ansible_host=192.168.1.103 ansible_user=root db2 ansible_host=192.168.1.104 ansible_user=root ``` 上述示例中,`[web_servers]`和`[db_servers]`都是组名,`web1`、`web2`、`db1`和`db2`都是主机名。`ansible_host`是主机的IP地址,`ansible_user`是登录主机的用户名。 动态主机清单的写法如下: ``` #!/usr/bin/env python import boto3 import json # Connect to EC2 ec2 = boto3.client('ec2') # Get all running instances instances = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) # Build host list hosts = [] for reservation in instances['Reservations']: for instance in reservation['Instances']: # Get public DNS name public_dns_name = instance['PublicDnsName'] if instance['PublicDnsName'] else instance['PrivateDnsName'] # Add to host list hosts.append(public_dns_name) # Print host list in JSON format print(json.dumps({'all': {'hosts': hosts}})) ``` 上述示例使用Python脚本动态获取AWS EC2中所有运行中的实例,并将其作为主机清单。运行脚本后,会输出一个JSON格式的主机清单文件,可以直接使用该文件作为Ansible主机清单。 无论是静态主机清单还是动态主机清单,都需要确保主机清单文件的格式正确,并且主机信息准确无误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

识途老码

赞赏是第一生产力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值