Ansible include_vars如果文件未找到则继续执行

9
如果我有这样的东西:
- include_vars: this_file_doesnt_exist.yml

ansible会抛出错误 "input file not found at ..." 并停止配置过程。

我想知道是否可以 在文件不存在的情况下允许配置过程继续

我的用例如下:

  • 尝试加载变量文件
  • 如果这些变量存在,则执行任务

示例:

- include_vars: aptcacher.yml

- name: use apt-cache
  template: src=01_proxy.j2 dest=/etc/apt/apt.conf.d/01_proxy owner=root group=root mode=644
  sudo: true
  when: aptcacher_host is defined

Ansible版本:1.9.1

3个回答

5

include_vars任务上,您可以直接忽略错误:

- include_vars: nonexistant_file
  ignore_errors: yes

编辑

使用ansible > 1.6.5时,我遇到了以下问题:

test.yml

---

- hosts: localhost
  tasks:
    - include_vars: nonexistent_file
      ignore_errors: yes

    - debug:
        msg="The show goes on"

播放 [本地主机]


获取信息 *************************************************************** 完成: [本地主机]

任务: [include_vars 不存在的文件] ***************************************** 失败: [本地主机] => {"failed": true, "file": "/home/ilya/spielwiese/ansible/nonexistent_file"} msg: 找不到源文件。...忽略

任务: [debug msg="秀必继续"] ****************************************** 完成: [本地主机] => { "msg": "秀必继续" }


1
我已经尝试使用“ignore_errors”,但似乎不起作用。Ansible将抛出相同的错误“在...找不到输入文件”。谢谢。 - joao cenoura
你正在使用 include_vars 作为任务吗?你尝试过我上面发布的playbook了吗? - ProfHase85
哦,这绝对不是 ansible 的调用方式(只是想知道其他任何东西是否适用于您)。您需要使用 -i 指定一个清单文件(并且不应该有逗号)。所以调用会像这样:ansible-playbook test.ymlansible-playbook -i /path/to/inventory test.yml - ProfHase85
你的库存文件应该包含类似 localhost ansible_connection=local 的内容(请参阅文档)。 - ProfHase85
以那种方式调用ansible是有原因的:查看这个这个或者在谷歌上搜索“如何在没有清单的情况下运行ansible”。 无论哪种方式都不起作用。 关于“如果其他任何东西与我一起工作”:是的,除了这部分。 我目前的怀疑是不同的版本。谢谢。 - joao cenoura
显示剩余2条评论

1
你可以使用 with_first_found 来实现这个功能。
- include_vars: "{{ item }}"
  with_first_found:
   - this_file_doesnt_exist.yml

我不确定如果没有至少一个文件匹配,它是否能正常工作而不抱怨。如果它不能正常工作,你需要添加一个空的备用文件:

- include_vars: "{{ item }}"
  with_first_found:
   - this_file_doesnt_exist.yml
   - empty_falback.yml

1
第一个情况不起作用,它需要至少匹配一个文件(输出“未给出源文件”)。第二种情况确实可以工作,但听起来更像是一种变通方法而不是一个适当/清洁的解决方案。谢谢! - joao cenoura

0
要可选地包含变量,您可以使用基于ansible.builtin.first_found查找的with_first_found循环。通过skip: true,您可以断言当它找不到任何文件时不会出错。
- include_vars: '{{ item }}'
  with_first_found:
    - files:
        - this_file_doesnt_exist.yml
      skip: true

从Ansible 2.2开始,您还可以使用正则表达式模式来包含文件。如果模块找不到任何文件,它将不会报错。注意:您必须提供一个确实存在的目录名称。
- include_vars:
    dir: vars
    files_matching: this_file_doesnt_exist.yml

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接