合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
# 变量与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`。