Ansible:如何测试已注册变量的条件?

Ansible:如何测试已注册变量的条件?

尝试使用 Ansible 定位并将 user_01 的所有文件所有权更改为 user_02?

  - name: "Find files for user_01 or UID of user_01_uid"
    command: "find / -path /proc -prune -o -path /sys -prune -o  \\( -user user_01 \\) -o  \\( -uid user_01_uid \\)"
    # escape character "\" prior to backslash character "\"   \\. Spacing to work with Ansible CentOS 7
    ignore_errors: yes
    register: files_2_change

  - name: "Display files_2_change"
    debug:
      msg: "{{ files_2_change.stdout_lines }}"

  - name: "Change owner & group permissions"
    file: 
      path: "{{ files_2_change.stdout_lines }}"
      owner: user_02
      group: user_02
      mode: 0760
      modification_time: preserve   # now
    when: 
      - files_2_change != '/proc'
      - files_2_change != '/sys'


    # Better soln for chown
    # command: "chown -h -R --from=user_01:user_01 user_02:user_02 {{ files_2_change.stdout_lines }}"

答案1

问题在于,你试图对整个files_2_change变量执行条件检查,而你真正感兴趣的是对你正在迭代的列表的每个元素执行条件检查。不幸的是,由于Ansible 如何处理循环中的条件,您不能只是循环file模块并每次进行检查。

我的建议是在实际任务之前添加一个额外的处理任务,file使用 Python 列表推导删除不需要的路径:

- name: "Process files_2_change, dropping unwanted files"
  set_fact:
    processed_files_2_change: >
      {{ processed_files_2_change | default([]) +
        [ item ] if '/proc' not in item and '/sys' not in item else []
      }}
  loop: "{{ files_2_change.stdout_lines }}"

- name: "Change owner & group permissions"
  file: 
    path: "{{ item }}"
    owner: user_02
    group: user_02
    mode: 0760
    modification_time: preserve
  loop: "{{ processed_files_2_change }}"

答案2

属性小路在模块中文件需要字符串。列表应该会失败。

致命:[localhost]:失败!=> {“msg”:“模板字符串时出现模板错误:意外的')'。字符串:{{files_2_change.stdout_lines))”}

(同样的方式已处理文件 2 更改

也可以循环列表。

- name: "Change owner & group permissions"
  file: 
    path: "{{ item }}"
    owner: user_02
    group: user_02
    mode: 0760
    modification_time: preserve   # now              
  loop: "{{ files_2_change.stdout_lines }}"
  when: 
    - item is not search('^/proc')
    - item is not search('^/sys')

(未经测试)

笔记

  • 使用寻找而不是“命令:“查找...”
  • 如果有目录文件_2_change.stdout_lines模式模式:0760将使它们无法被群组访问。

答案3

更新:这是我根据此处的反馈目前得到的信息(2019 年 7 月 17 日)。

将 /var/spool/mail 添加到排除项中。

目前的测试似乎有效。

  - name: "Find files for user_X or UID of user_X_uid"
    command: "find / -path /proc -prune -o -path /sys -prune -o  \\( -user user01 \\) -o  \\( -uid 1051 \\)"
    ignore_errors: yes
    register: files_2_change


  - name: "Change owner & group permissions"
    file: 
      path: "{{ item }}"
      owner: user02
      group: user02
      mode: 0771          # If there are directories - 0760 will make them not accessible for the group.
      modification_time: preserve
    loop: "{{ files_2_change.stdout_lines }}"
    when: 
      - item is not search('^/proc')
      - item is not search('^/sys')
      - item is not search('^/var/spool/mail')

感谢大家的意见和帮助!

相关内容