如何在角色的变量文件中使用Ansible事实变量

时间:2019-07-23 08:43:38

标签: ansible

我正在编写一个角色,以在Linux服务器上配置Shorewall,我想在角色的ansible_default_ipv4.interface文件中使用default/main.yml发现的变量,然后通过template模块使用。

>

我现在有这样的东西,它不起作用:

linux_server_shorewall_interfaces:
  - { zone: net, iface: {{ ansible_default_ipv4.interface }}, options: "routefilter,tcpflags", comment: "net_<interface>" }

错误是:

   ERROR! Syntax Error while loading YAML.
     found unacceptable key (unhashable type: 'AnsibleMapping')

   The error appears to have been in '/tmp/kitchen/roles/linux_server/defaults/main.yml': line 59, column 26, but may
   be elsewhere in the file depending on the exact syntax problem.

   The offending line appears to be:

   linux_server_shorewall_interfaces:
     - { zone: net, iface: {{ ansible_default_ipv4.interface }}, options: "routefilter,tcpflags", comment: "net_<interface>" }
                     ^ here
   We could be wrong, but this one looks like it might be an issue with
   missing quotes.  Always quote template expression brackets when they
   start a value. For instance:

       with_items:
         - {{ foo }}

   Should be written as:

       with_items:
         - "{{ foo }}"

我希望在文件文件中看到net ens32 routefilter,tcpflags

1 个答案:

答案 0 :(得分:0)

{{ansible_default_ipv4.interface}} has to be quoted的扩展(single-quotation更简单)。下面的游戏

- hosts: localhost
  gather_facts: yes
  tasks:
    - set_fact:
        linux_server_shorewall_interfaces:
          - { zone: 'net',
              iface: '{{ ansible_default_ipv4.interface }}',
              options: 'routefilter,tcpflags',
              comment: 'net_<interface>' }
    - debug:
        var: linux_server_shorewall_interfaces

给予

ok: [localhost] => {
    "linux_server_shorewall_interfaces": [
        {
            "comment": "net_<interface>", 
            "iface": "wlan0", 
            "options": "routefilter,tcpflags", 
            "zone": "net"
        }
    ]
}