Ansible笔记
Inventory文件
内置参数
- ansible_ssh_host 将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.
- ansible_ssh_port ssh端口号.如果不是默认的端口号,通过此变量设置.
- ansible_ssh_user 默认的 ssh 用户名
- ansible_ssh_pass ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)
- ansible_sudo_pass sudo 密码(这种方式并不安全,我们强烈建议使用 --ask-sudo-pass)
- ansible_sudo_exe (new in version 1.8) sudo 命令路径(适用于1.8及以上版本)
- ansible_connection 与主机的连接类型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默认使用 paramiko.1.2 以后默认使用 ‘smart’,‘smart’ 方式会根据是否支持 ControlPersist, 来判断’ssh’ 方式是否可行.
- ansible_ssh_private_key_file ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.
- ansible_shell_type 目标系统的shell类型.默认情况下,命令的执行使用 ‘sh’ 语法,可设置为 ‘csh’ 或 ‘fish’.
- ansible_python_interpreter 目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不是"/usr/bin/python",比如 *BSD, 或者 /usr/bin/python不是 2.X 版本的 Python.我们不使用 “/usr/bin/env” 机制,因为这要求远程用户的路径设置正确,且要求 “python” 可执行程序名不可为 python以外的名字(实际有可能名为python26).与 ansible_python_interpreter 的工作方式相同,可设定如 ruby 或 perl 的路径…
主机与组及变量
- 主机与组的形式
- [组名1]
ip IP形式
name 域名形式
ip:port IP加端口形式
name:port 域名加端口形式 - [组名2]
jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50 别名配置形式
www[01:50].example.com 多主机数组形式 - [组名3]
db-[a:f].example.com 多主机数组形式
other2.example.com ansible_connection=ssh ansible_ssh_user=mdehaa 配置连接类型及用户名等 - [组名4] 把一个组作为另一个组的子成员
组名1
组名2
- [组名1]
- 主机变量
- 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
注:主机变量优先级高于主机组变量,给定的主机组变量优先级高于all特殊组
- [atlanta]
分文件定义 Host 和 Group 变量
在 inventory 主文件中保存所有的变量并不是最佳的方式.还可以保存在独立的文件中,这些独立文件与 inventory 文件保持关联. 不同于 inventory 文件(INI 格式),这些独立文件的格式为 YAML
- 假设 inventory 文件的路径为:
/etc/ansible/hosts,默认主机清单文件 - 假设有一个主机名为 ‘foosball’, 主机同时属于两个组,一个是 ‘raleigh’, 另一个是 ‘webservers’. 那么以下配置文件(YAML 格式)中的变量可以为 ‘foosball’ 主机所用.依次为 ‘raleigh’ 的组变量,’webservers’ 的组变量,’foosball’ 的主机变量:
/etc/ansible/group_vars/raleigh
/etc/ansible/group_vars/webservers
/etc/ansible/host_vars/foosball- 示例
- 主机清单
[test]
test1 test1var=t1
test2
[test:vars]
test2var=t2 - 组变量(变量名文件与组名相同,变量名目录与组名相同)
/etc/ansible/group_vars/test.yaml(.json/.yml)
/etc/ansible/group_vars/test/a.yaml
test3var: t3 - 示例剧本 exapmle.yml
- hosts: test1
tasks:
- debug:
msg: “{{test1var}}”
- debug:
msg: “{{test2var}}”
- debug:
msg: “{{test3var}}” - 执行结果ansible-playbook exapmle.yml
PLAY [test1] ******************************************
TASK [Gathering Facts] ***********************************
ok: [test1]
TASK [debug] ******************************************
ok: [test1] => {
“msg”: “t1”
}
TASK [debug] ******************************************
ok: [test1] => {
“msg”: “t2”
}
TASK [debug] ******************************************
ok: [test1] => {
“msg”: “t3”
}
PLAY RECAP ******************************************
test1 : ok=4 changed=0 unreachable=0 failed=0
- 主机清单
- 示例