# 变量与facts
## playbook中变量将优先级
- playbook的yml文件中使用var定义
- 通过--extra-vars命令行给变量赋值
- 在vars/vars\_files文件中定义变量
- 注册变量
## 注册变量 [debug](http://docs.ansible.com/ansible/latest/debug_module.html) \[register\]\[2\]
debug的具体用法参见debug模块
```
- name: show return value of cmd
hosts: test
tasks:
- name: capture output of cmd
command: id -un
register: login
- debug: var=login # 此处debug中赋值,可以查看到详细信息
- debug: msg="{{ login.stdout }}"
```
## fact
```
# 不收集客户端状态信息
gather_facts: false
```
### 查看与某台服务器关联的所有fact
Ansible使用setup模块来收集fact,在playbook可以直接使用setup收集的变量,也可以在命令行手动调用。
```
ansible test -m setup
ansible test -m setup -a "filter=ansible_eth*"
```
```
- name: show return value of cmd
hosts: localhost
- debug:
msg: "{{ hostvars[inventory_hostname] }}"
```
### 本地fact
可以在/etc/ansible/facts.d目录中定义本地fact文件
#### 定义
/etc/ansible/facts.d/example.fact
```
[book]
title=Ansible Up and Running
author=Lorin
```
#### 调用
测试未通过
```
- debug: var=ansible_local
- debug: msg="The book is {{ ansible_local.example.book.title }}"
```
### [set\_fact](http://docs.ansible.com/ansible/latest/set_fact_module.html)定义新变量
```
- name: show return value of cmd
hosts: test
tasks:
- name: capture output of cmd
command: id -un
register: login
- set_fact: new_var={{ login.stdout }}
- debug: var=new_var
```
## 内置变量
在playbook中永远可以访问的变量
```
inventory_hostname # 被ansible所识别的当前主机的名称,如果定义过别名,则是别名
hostvars # 字典, key为主机名,value为对应主机的参数,如 {{ hostvars['db.example.com'].ansible_eth1.ipv4.address }}
group_names # 当前主机所属群列表
groups # 字典, key为群组名,value为群成员组成的主机名列表,包括all和ungrouped分组,如{"all": [...], "web": [...], "ungrouped": [...]}
play_hosts # 当前play涉及的主机的invetory主机名
ansible_version # ansible的版本信息
```
### 示例
```
- debug: msg={{ hostvars['testserver'].ansible_ens33.ipv4.address }}
```
使用在templates中
```
{% for host in groups.web %}
server {{ host.inventory_hostname }} {{ host.ansible_ens33.ipv4.address }}:80
{% endfor %}
```
## 在命令行设置变量
在命令行中使用`-e key=value`。
- 目录
- ansible基础
- ansible简介
- ansible安装和测试
- ansible配置文件
- yaml在ansible中的用法
- inventory
- 变量与facts
- when语句
- handler模块
- 大杂烩
- ansible模块
- copy模块
- cron模块
- debug模块
- django_manage模块
- file模块
- git模块
- hostname模块
- lineinfile模块
- mysql_user模块
- mysql_db模块
- pip模块
- selinux
- setup模块
- shell 和 command模块
- stat模块
- supervisorctl
- systemd
- timezone
- unarchive模块
- user模块
- wait_for
- yum和service模块
- 其他模块或者方法
- 其他
- 报错处理
- playbooks
- 复杂的playbook
- 循环
- roles