【问题标题】:Trying to run stat over a list if directories and perform some action if they exist in Ansible如果目录存在,则尝试在列表上运行 stat 并执行某些操作(如果它们存在于 Ansible 中)
【发布时间】:2021-03-14 20:08:19
【问题描述】:

我是 Ansible 新手,所以请多多包涵。

我有一个需要设置 FACL 的目录列表。 并非所有这些目录都存在于我的清单中的所有主机上。我的 Ansible 剧本试图实现以下目标:

-stat 列出dir_list 变量文件中的每个目录并注册结果。 - 运行 acl 模块为服务器上存在的任何目录分配 FACL 权限。

这是我的变量文件 - dir_list - 的样子:

dir_path:
  - /tmp/testdir1
  - /tmp/testdir2
  - /tmp/testdir3
  - /tmp/testdir4

这是我的剧本的样子:

---
- hosts: localhost
  connection: local
  become: yes
  become_method: sudo
  become_user: root
  gather_facts: yes
  any_errors_fatal: no
  vars_files:
    - /home/user1/ansible/dir_list
  tasks:
  - name: Check if directory exists
    stat:
      path: "{{ item }}"
    with_items:
      "{{ dir_path }}"
    register: dircheck

  - name: Set ACLs
    acl:
      path: "{{ item }}"
      entity: testuser
      etype: user
      permissions: rx
      state: present
    with_items: "{{ dircheck.results | selectattr('stat.isdir') | map(attribute='item') | list }}"
    when: item.stat.isdir is defined and (item.stat.isdir|bool)

我显然已经对此进行了研究,并尝试了十几种建议的解决方案,但均无济于事。最后两行只是我尝试过的无数组合中的两种。我在 RHEL7 上运行 Ansible 2.9.10 版。

任何帮助将不胜感激。

【问题讨论】:

  • Ansible 的反馈是什么样的?

标签: ansible ansible-2.x


【解决方案1】:

问:"统计 dir_list 变量中列出的每个目录...运行 acl 模块以将 FACL 权限分配给任何存在的目录。"

A:给定目录

shell> ls -d1 /tmp/* | grep testdir
/tmp/testdir1
/tmp/testdir2
/tmp/testdir3

剧本

- hosts: localhost
  vars:
    dir_path:
      - /tmp/testdir1
      - /tmp/testdir2
      - /tmp/testdir3
      - /tmp/testdir4
  tasks:
    - stat:
        path: "{{ item }}"
      loop: "{{ dir_path }}"
      register: dircheck
    - debug:
        msg: "Set ACLs at {{ item.stat.path }}"
      loop: "{{ dircheck.results }}"
      loop_control:
        label: "{{ item.item }}"
      when:
        - item.stat.exists
        - item.stat.isdir|default(false)

给予(删节)

TASK [stat] ****
ok: [localhost] => (item=/tmp/testdir1)
ok: [localhost] => (item=/tmp/testdir2)
ok: [localhost] => (item=/tmp/testdir3)
ok: [localhost] => (item=/tmp/testdir4)

TASK [debug] ****
ok: [localhost] => (item=/tmp/testdir1) => 
  msg: Set ACLs at /tmp/testdir1
ok: [localhost] => (item=/tmp/testdir2) => 
  msg: Set ACLs at /tmp/testdir2
ok: [localhost] => (item=/tmp/testdir3) => 
  msg: Set ACLs at /tmp/testdir3
skipping: [localhost] => (item=/tmp/testdir4)

【讨论】:

  • 像魅力一样工作!谢谢弗拉基米尔。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
  • 2013-02-12
  • 2021-10-27
相关资源
最近更新 更多