ansible ansible
inventory
群组
ansible自动定义了一个群组叫all(或\*),它包括inventory中所有主机。
群组可嵌套:
[django:children]
web
task
对主机编号后,写成群组很方便:
[web]
web[1:20].example.com
[web]
web-[a-t].example.com
可以指定群组变量:
[all:vars]
ntp_server=ntp.ubuntu.com
[production:vars]
db_primary_host=rhodeisland.example.com
db_primary_port=5432
动态inventory
动态inventory脚本必须支持以下两个命令行参数:
`` example
--host=
--list for listing groups
–host的输出要包含所有主机特定的变量。–list返回的json的键名为"<sub>meta</sub>"。
<h3 id="运行时添加条目">运行时添加条目</h3>
在playbook执行时创建了新的主机,要把这个新的主机加入inventory的话,只能使用add<sub>host</sub>。
group<sub>by也是在playbook运行时创建群组</sub>。
<h2 id="变量">变量</h2>
<h3 id="注册变量">注册变量</h3>
可以将命令的输出捕获到名为login的变量中:
yaml
- name: capture output of whoami command
command: whoami
register: login
输出的变量的结构由模块决定。
<h3 id="查看fact">查看fact</h3>
查看某台主机的fact:
example
ansible server1 -m setup
查看fact的子集:
example
ansible web -m setup -a 'filter=ansible_eth*'
<h3 id="模块返回fact">模块返回fact</h3>
如果模块返回一个字典且包含名为ansible<sub>facts的key</sub>,那么ansible将会根据对应的valude创建相应的变量,并分配给相应的主机。对于返回fact的模块,并不需要使用注册变量。
<h3 id="本地fact">本地fact</h3>
如果目标主机的/etc/ansible/facts.d目录下有以下形式的文件:
- .ini
- json
- 返回json的可执行程序
ansible会将其加载到名为ansible<sub>local的特殊变量上</sub>。
<h3 id="set<sub>fact设置变量</sub>">set<sub>fact设置变量</sub></h3>
在register之后再使用set<sub>fact</sub>,就能很好地将上一task的结果传递到下一task。
<h3 id="内置变量">内置变量</h3>
- hostvars
web服务器上运行的task会需要数据库服务器主机上的ip,此时就要用到hostvars变量了。这个字典包含了所有主机上定义的所有变量,并以ansible识别的主机名作为key。如果ansible还未采集fact,并且没有fact缓存,那么就无法访问了。
example
{{hostvars['db.example.com'].ansible_eth1.ipv4.address}}
- inventory<sub>hostname</sub>
ansible所识别的当前主机的主机名,如果有别名,那就是别名。利用hostvars和inventory<sub>hostname</sub>,可以输出与当前主机关联的所有变量:
example
- debug: var=hostvars[inventory_hostname]
- groups
配置web群组中所有服务器的IP地址:
backend web-backend
{% for host in groups.web %}
server {{ host.inventory_hostname }} {{ host.ansible_default_ipv4.address }}:80
{% endfor %}
<h2 id="handler">handler</h2>
yaml
- name: copy TLS key
copy: src=files/nginx.key dest={{ key_file }} owner=root mode=0600
notify: restart nginx
handlers:
- name: restart nginx
service: name=nginx state=restarted
handler只会在所有任务执行完成后执行,即使被通知了多次,它也只会执行一次。handler按照play中定义的顺序执行,而不是被通知的顺序。常见的handler用法就是重启服务。
<h2 id="ansible-doc">ansible-doc</h2>
example
ansible-doc -l
ansible-doc file