任务中动态变量的 Ansible 角色检查路径

Ansible role checking path of dynamic variable within task

我有几个 ansible 角色任务,我用它们来设置一些配置目录。问题是我有一个配置列表,需要使用特定路径进行设置,但前提是它们不存在。

- name: Ensure core configuration directories exist.
  shell: "cp -r {{ service_install_path }}/conf/ {{ service_home }}/{{ item }}.conf.d"
  when: 
    - "item in conf_indexes_current.content"
    - "not {{ service_home }}/{{ item }}.conf.d.stat.exists"
  with_items: "{{ conf_dirs }}"

然而,问题是您不能像这样统计路径:

    - "not {{ service_home }}/{{ item }}.conf.d.stat.exists"

我得到的错误是:

The conditional check 'not {{ service_home }}/{{ item }}.conf.d.stat.exists' failed. The error was: unexpected '/' line 1

有没有办法设置一个动态变量全路径然后测试?看来我也不能在这里设置一个事实。

[update]:刚刚阅读了另一个问题,试图用一个非常模糊的相似循环概念做一些事情。此时简单地使用 shell script/template 是正确的方法吗?

好吧,我最终确实通过其他 Stack 问题和随机站点的点点滴滴的提示解决了这个问题。我不经常使用 ansible,我们只用了大约一年。我最终做了以下事情,把它分成了两个任务:

- name: Check existence of config for each index.
  stat: 
    path: "{{ service_home }}/{{ item }}.conf.d"
  register: "{{ item }}_conf_true"
  with_items: "{{ conf_dirs }}"

- name: Ensure core configuration directories exist as full templates for modification.
  shell: "cp -r {{ service_install_path }}/conf/ {{ service_home }}/{{ item }}.conf.d"
  when: 
    - "item in conf_indexes_current.content"
    - "{{ item }}_conf_true is not defined"
  with_items: "{{ conf_dirs }}"

有用吗?是的。合适吗?也许吧,但可能有更好的方法我还没有想到或看到过。