下面是我的剧本:
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播放无法在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”。
任何解决方案将不胜感激。
如果作为条目/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"
}
因此,如果您传递包含扩展名的条目:
$ ansible localhost -m debug -a "msg={{ (item | splitext)[1].split('.')[1] }}" -e item=/toto/pipo.test
localhost | SUCCESS => {
"msg": "test"
}
同时,当表达式本身不返回值时,您可以设置默认值:
$ ansible localhost -m debug -a "msg={{ (item | splitext)[1].split('.')[1] | default('') }}" -e item=/toto/pipo
localhost | SUCCESS => {
"msg": ""
}