通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
## playbook中变量将优先级 * playbook的yml文件中使用var定义 * 通过--extra-vars命令行给变量赋值 * 在vars/vars_files文件中定义变量 * 注册变量 ## 注册变量 [debug][1] [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][3]定义新变量 ~~~ - 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`。 [1]:http://docs.ansible.com/ansible/latest/debug_module.html [3]:http://docs.ansible.com/ansible/latest/set_fact_module.html