Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 具有未定义变量的可分解模板_Linux_Loops_Automation_Ansible - Fatal编程技术网

Linux 具有未定义变量的可分解模板

Linux 具有未定义变量的可分解模板,linux,loops,automation,ansible,Linux,Loops,Automation,Ansible,我有一个包含我在剧本中使用的变量的文件: net_interfaces: ... - name: "eth0" ip: "192.168.1.100" mask: "255.255.255.0" gateway: "192.168.1.1" ... 我想用这些变量部署一些配置,例如ifcfg-eth0: 但有时,项没有网关变量,在这种情况下,我想删除字符串 GATEWAY={{ item.gateway }} 从目标计算机上的此配置文件。如何在不为特定主机

我有一个包含我在剧本中使用的变量的文件:

net_interfaces:
  ...
  - name: "eth0"
    ip: "192.168.1.100"
    mask: "255.255.255.0"
    gateway: "192.168.1.1"
  ...
我想用这些变量部署一些配置,例如ifcfg-eth0:

但有时,没有网关变量,在这种情况下,我想删除字符串

GATEWAY={{ item.gateway }}
从目标计算机上的此配置文件。如何在不为特定主机创建另一个任务的情况下实现此目标?

添加条件:

{% if item.gateway is defined %}
GATEWAY={{ item.gateway }}
{% endif %}
另一种(也是更好的)方法是使用“默认”过滤器,因为在这种情况下,我们可以检查是否定义了某个变量,如果没有定义,则设置它的默认值。例如:

{{ my_string_value | default("awesome") }}

谢谢你的回答!在这种情况下,如果条件允许,你可以告诉我怎么排一行吗?我尝试了
{{--gateway={{{{{{item.gateway}}}如果item.gateway已定义}
但是我在输出中得到了这个字符串:--gateway={{{{item.gateway}找到了唯一的方法:
{%if item.gateway已定义%}gateway={{{item.gateway}{%endif%}
您可以使用-}而不是%}来抑制输出中的换行,所以它仍然是生成文件中的一行。
{{ my_string_value | default("awesome") }}