简体   繁体   English

Jinja2模板中的Ansible CSV查找,如何处理丢失的密钥

[英]Ansible CSV lookup in Jinja2 template, how to handle missing key

j2 template and here is a snippet: j2模板,这是一个代码段:

{% set denyGroups %}
{{lookup('csvfile', '{{ ansible_hostname }} file={{ csvFile }} delimiter=, col=5')}}
{% endset %}
{%- if denyGroups |trim() -%}
simple_deny_groups = {{ denyGroups |replace(";", ",") }}
{%- endif -%}

I am injecting values into the template based on csv values. 我正在基于csv值将值注入模板。 However, if the key (ansible_hostname ) is not found in the csv, get this error: AnsibleError: csvfile: list index out of range 但是,如果在csv中找不到键(ansible_hostname),则会出现此错误: AnsibleError: csvfile: list index out of range

How can I do this error handling? 我该如何处理错误? Check if its in the csv first. 首先检查其是否在csv中。 Now I could inject the value in tasks, but that will be a bit more cumbersome, and I prefer this template way. 现在,我可以将值注入任务中,但这会比较麻烦,并且我更喜欢这种模板方式。 Thanks 谢谢

list index out of range – it's a problem with number of columns. list index out of range –这是列数的问题。
Columns are counted from zero, so for col=5 – there must be 6 columns in the file. 列从零开始计数,因此对于col=5 –文件中必须有6列。
If you want to return a default item if key is missing, use default=myvalue option. 如果要在缺少键的情况下返回默认项目,请使用default=myvalue选项。

Update: Let's look into the code : 更新:让我们看一下代码

def read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1):

    try:
        f = open(filename, 'r')
        creader = CSVReader(f, delimiter=to_bytes(delimiter), encoding=encoding)

        for row in creader:
            if row[0] == key:
                return row[int(col)]
    except Exception as e:
        raise AnsibleError("csvfile: %s" % to_str(e))

    return dflt

So in the csv like this: 所以在这样的csv中:

mykey,val_a,val_b.val_c

key (column 0) is mykey, column 1 - val_a, column 2 - val_b, column 3 - val_c. 键(第0列)是mykey,第1列-val_a,第2列-val_b,第3列-val_c。

If there is a format error or your parameters are incorrect, exception will be triggered – you can't do anything about it. 如果存在格式错误或您的参数不正确,则会触发异常-您无法对此做任何事情。 Trying to use col=4 with my example csv file will rise list index out of range exception. 尝试在我的示例csv文件中使用col=4将导致list index out of range异常。

If the key is not found in the file ( row[0] == key was false for every line), default value will be returned (the one you specify with default= option). 如果在文件中未找到键( row[0] == key对于每一行都是false),则将返回默认值(使用default=选项指定的键)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM