首页 > 解决方案 > Touch log file with Ansible only when it does not start with __

问题描述

Using Ansible 2.7.13, I'm trying to perform a touch of logfiles in a list only if the filename does start with __. I cannot seem to get it running.

Here's my code:

# file touch.yml
- name: Touch
  file:
    path: "{{ item }}"
    state: touch
    mode: '0777'
  when: not (item | basename | regex_search("^__"))
  with_items:
    - "{{ touch_files }}"

I call this with

touch_files:
        - "{{ path }}/job_count.json"
        - "{{ path }}/query_time.json"
        - "{{ path }}/disk_usage.json"
        - "{{ path }}/__revert__"

Which results in :

ERROR! 'when' is not a valid attribute for a Play[0m
The error appears to have been in '... /playbooks/touch.yaml': line 3, column 3, but may be elsewhere in the file depending on the exact syntax problem.

Expected result: files listed in the touch_files list are touched. The __revert__ file is not touched.

What could be the problem here?

Many thanks in advance!

标签: ansible

解决方案


Q: "Perform a touch of logfiles in a list only if the filename does start with __ "

A: There are problems in the code

  • when shall be used outside the loop
  • touch_files is a list; loop list of lists can't work
  • when condition is wrong

Try the task below

- name: Touch
  file:
    path: "{{ item }}"
    state: touch
    mode: '0777'
  loop: "{{ touch_files }}"
  when: "item|basename is regex('^__(.*)$')"

(not tested)


推荐阅读