VPS测评 VPS推荐 VPS优惠
Linux运维

Ansible相关文件和Inventory配置

Ansible的主要配置文件路径以及Inventory file的格式说明

Ansible配置文件

  • /etc/ansible/ansible.cfg 主配置文件
  • /etc/ansible/hosts 主机清单
  • /etc/ansible/roles/ 存放角色的目录

Ansible 主配置文件

Ansible 的配置文件可以放在多个不同地方,优先级从高到低顺序如下:

ANSIBLE_CONFIG    #环境变量,注意此项用 ansible --version 看不到,但可以生效
./ansible.cfg   #当前目录下的ansible.cfg
~/.ansible.cfg   #当前用户家目录下的.ansible.cfg
/etc/ansible/ansible.cfg   #系统默认配置文件

inventory 主机清单文件

官方文档直达:https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html

Ansible的主要功用在于批量操作主机,为了便捷地使用其中的部分主机,可以在inventory 主机清单文件中将其分组。

默认的inventory file为:

/etc/ansible/hosts

inventory file可以有多个,在执行命令时使用 -i <path> 来指定。

主机清单文件格式

  • inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中。
  • 此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明。
  • 如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机。

Inventory 参数说明

ansible_ssh_host #将要连接的远程主机名
ansible_ssh_port #ssh端口号,如果不是默认的端口号,通过此变量设置
ansible_ssh_user #默认的ssh用户名
ansible_ssh_pass #ssh密码(此方法不安全)
ansible_sudo_pass #sudo密码(此方法不安全)
ansible_connection #与主机的连接类型local,ssh,paramiko
ansible_ssh_private_key_file #ssh使用的私钥文件,适用于有多个密钥,而你不想使用SSH代理的情况
ansible_shell_type #目标系统的shell类型,默认sh
ansible_python_interpreter #目标主机的python路径

范例:中括号表示组名

mail.frog.com

[webservers]
www1.frog.com:2222
www2.frog.com

[dbservers]
db1.frog.com
db2.frog.com
db3.frog.com
#也可指定范围,不用单独一个个列出
db[1:3].frog.com

范例: 组嵌套

[webservers]
www[1:100].frog.com

[dbservers]
db-[a:f].frog.com

#可以定义范围的步长,每次加2
[appservers]
10.0.0.[1:100:2]

#testsrvs组中包括两个子组,实现组嵌套
[testsrvs:children]
webservers
dbservers

范例: 为特定的主机设置变量

[test]
10.0.0.8 ansible_connection=local #指定本地连接,无需ssh配置
10.0.0.7 ansible_connection=ssh ansible_ssh_port=2222 ansible_ssh_user=root ansible_ssh_password=xxx
10.0.0.6 ansible_connection=ssh ansible_ssh_user=root ansible_ssh_password=xxx

范例: 定义别名

[websrvs]
web1 ansible_ssh_host=10.0.0.101
web2 ansible_ssh_host=10.0.0.102

范例:设置组变量,对组中的所有主机生效

[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com
未经允许不得转载:青蛙主机 » Ansible相关文件和Inventory配置

VPS相关常用工具

PING测试工具自用毛子接码站