如何解决Ansible“ with_lines:cat somefile”在跳过的块中失败
我有一个剧本,其中一个块具有when条件。内部是一个带有循环的任务。如何更改此循环,以便在条件为false时跳过的任务不会失败?
block:
- name: create a file
lineinfile:
line: "Hello World"
path: "{{my_testfile}}"
create: yes
- name: use the file
debug:
msg: "{{ item}}"
with_lines: cat "{{my_testfile}}"
when: false
TASK [create a file] ************************************************************************************************************************************************************
TASK [use the file] *************************************************************************************************************************************************************
cat: files/my/testfile: No such file or directory
fatal: [ipad-icpi01]: FAILED! => {"msg": "lookup_plugin.lines(cat \"files/mytestfile\") returned 1"}
解决方法
将失败的任务更改为以下命令,即使该文件不存在,该任务也将始终可以运行,并且在不需要的情况下将不使用shell或命令:
- name: use the file
debug:
msg: "{{ item }}"
loop: "{{ (lookup('file',my_testfile,errors='ignore') | default('',true)).split('\n') }}"
要点:
- 将
file
查找插件与errors='ignore'
一起使用,以便它返回文件内容或None
而不是文件不存在时的错误。 - 使用
default
过滤器和true
的第二个选项,以便在var存在但为空或为空的情况下返回默认值。 - 将结果分成新行以获取行列表(如果文件不存在,则为空列表)。
注意:正如@Vladimir所报告的,我更正了您的var名称,该名称在ansible中无效。
,测试文件是否存在。例如
- block:
- name: create a file
lineinfile:
line: "Hello World"
path: "{{ my_testfile }}"
create: yes
- name: use the file
shell: '[ -f "{{ my_testfile }}" ] && cat {{ my_testfile }}'
register: result
- name: use the file
debug:
msg: "{{ item }}"
loop: "{{ result.stdout_lines }}"
when: false
lookup
插件file
应该是首选。
最后我得到了所提供的答案。这些任务将被跳过,不会失败或不会发出警告。
- block:
- name: create a file
lineinfile:
line: "Hello World"
path: "{{ my_testfile }}"
create: yes
- name: get the file
slurp:
src: "{{ my_testfile }}"
register: result
- name: use the file
debug:
msg: "{{ item }}"
loop: "{{ (result['content'] | b64decode).split('\n') }}"
when: false
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。