1. 简介
Ansible通过一个hosts文件来定义主机信息,也就是所谓的Inventory,如果是通过yum安装的,则主机文件默认是/etc/ansible/hosts
,也可以通过-i
或--inventory-file
指定hosts文件,示例如下:
ansible -i hosts -m ping
hosts文件可以通过ini
的风格配置、也支持yaml
的格式,个人比较喜欢ini
的配置方式。
2. 主机与主机组
ansible有一个默认的主机组名为:all
,表示所有主机
- 常规配置
mail.example.com # 单个主机
[webservers] # 主机组
foo.example.com
bar.example.com
[dbservers]
one.example.com
two.example.com
three.example.com
- 定义范围:这种方式一般主机名比较规律,示例如下:
第一种方式:通过数字
# 数字01-10,如我有10台api server
# cat hosts
[baseapi]
web[01:10:2].server.com
# ansible all -i hosts --list-hosts
hosts (10):
web01.server.com
web02.server.com
web03.server.com
web04.server.com
web05.server.com
web06.server.com
web07.server.com
web08.server.com
web09.server.com
web10.server.com
# 在hosts中指定步长
[baseapi]
web[01:10:2].server.com
# ansible all -i hosts --list-hosts
hosts (5):
web01.server.com
web03.server.com
web05.server.com
web07.server.com
web09.server.com
第二种方式:通过字母
# cat hosts
[databases]
db-[a:f].server.com
# ansible all -i hosts --list-hosts
hosts (6):
db-a.server.com
db-b.server.com
db-c.server.com
db-d.server.com
db-e.server.com
db-f.server.com
3. 变量
- 给单台主机设置变量
[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909
- 给主机组设置变量
[atlanta]
host1
host2
[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com
4. 继承
可以利用:children
来组合多个主机组,为一个大组
[atlanta]
host1
host2
[raleigh]
host2
host3
[southeast:children] # 多个主机组
atlanta
raleigh
[southeast:vars] # 变量
some_server=foo.southeast.example.com
halon_system_timeout=30
self_destruct_countdown=60
escape_pods=2
[usa:children] # 组
southeast
northeast
southwest
northwest
5. 别名
使用别名的话,需要通过ansible_host指定主机,即key=value的形式,否则会报错
# cat hosts
proxy ansible_host=127.0.0.1
# ansible all -i hosts --list-hosts
hosts (1):
proxy
6. 内置的变量
常用的变量如下
变量配置 | 说明 |
---|---|
ansible_connection | 连接方式,可以用:smart、ssh或paramiko,默认是smart |
ansible_host | ssh主机 |
ansible_port | ssh端口,默认22 |
ansible_user | ssh用户 |
ansible_password | ssh密码 |
ansible_ssh_private_key_file | 指定ssh私钥文件 |
ansible_become | 等同于ansible_sudo或ansible_su,允许执行特权命令 |