由于 include_vars 文件中的未定义变量导致执行 ansible 播放时出现问题

Issue executing ansible play due to undefined variable in include_vars file

下面是我的剧本:

  tasks:
   - name: Construct File Path on Destination Server.
     include_vars:
       file: "{{ item }}"
     with_fileglob:
        - "vars/myvars.yaml"

   - name: setting_facts for BackEnd
     set_fact:
       fpath_BackEnd_APP: []
     set_fact:
       fpath_BackEnd_APP: "{{ fpath_BackEnd_APP + [ BASEPATH ~ '/' ~ vars[ (item | splitext)[1].split('.')[1] ] ~ '/' ~ item | basename ] }}"
     with_items:
       - "{{ Source_Filenames.split(',') }}"

这是我的变量文件:

cat vars/myvars.yaml

com: /path/to/com/folder
src: /path/to/src/folder

下面的剧本 运行 按预期工作正常。

ansible-playbook  /app/deploy.yml -e Source_Filenames=/app/testing_purpose.src,/app/testing_purpose.com

但是,当我传递没有点 (.) 的文件名时,即没有文件扩展名,ansible play 无法在 myvars.yaml 中找到变量,错误如下:

ansible-playbook  /app/deploy.yml -e Source_Filenames=/app/testing_purpose.src,/app/testing_purpose,/app/testing_purpose.com,/app/testing_moht

"The task includes an option with an undefined variable. The error was: list object has no element 1\n\nThe error appears to be in '/app/deploy.yml'"

我的要求是为变量 "fpath_BackEnd_APP" 分配“/path/to/no-ext/folder”,以防传递没有扩展名的文件。扩展名为 .com 和 .src 的文件工作正常,因为它们从 myvars.yml 文件中获取变量值。对于任何其他文件扩展名,如 .jpg 或 .txt 剧本应该出现变量未定义错误。 任何解决方案将不胜感激。

如果你作为一个条目/toto/pipo

$ ansible localhost -m debug -a "msg={{ (item | splitext) }}" -e item=/toto/pipo
localhost | SUCCESS => {
    "msg": "('/toto/pipo', '')"
}

$ ansible localhost -m debug -a "msg={{ (item | splitext)[1] }}" -e item=/toto/pipo
localhost | SUCCESS => {
    "msg": ""
}

$ ansible localhost -m debug -a "msg={{ (item | splitext)[1].split('.') }}" -e item=/toto/pipo
localhost | SUCCESS => {
    "msg": [
        ""
    ]
}

$ ansible localhost -m debug -a "msg={{ (item | splitext)[1].split('.')[1] }}" -e item=/toto/pipo
localhost | FAILED! => {
    "msg": "The task includes an option with an undefined variable. The error was: list object has no element 1"
}

然而,如果您传递的条目包含 /toto/pipo.test 这样的扩展名:

$ ansible localhost -m debug -a "msg={{ (item | splitext)[1].split('.')[1] }}" -e item=/toto/pipo.test
localhost | SUCCESS => {
    "msg": "test"
}

同时,当表达式本身没有 return 值时,您可以设置一个默认值:

$ ansible localhost -m debug -a "msg={{ (item | splitext)[1].split('.')[1] | default('') }}" -e item=/toto/pipo
localhost | SUCCESS => {
    "msg": ""
}