如何在“stat”提供的字典中遍历路径?

2024-05-20 13:42:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用ansible来确定路径集合中的哪一个存在,然后只对存在的路径执行一个操作(它不仅仅是下面示例中的copy,还可以进一步编辑)。 这是我想到的-这是第二次迭代,在第二个任务中使用with_item也无法获得任何工作。在

- name: disable plasma - identify files to act on
  stat:
    path: "{{ item }}"
  register:
    plasma_conf
  with_items:
    - "/usr/share/autostart/plasma-desktop.desktop"
    - "/usr/share/autostart/plasma-netbook.desktop"
    - "/etc/xdg/autostart/plasmashell.desktop"

- name: disable plasma - copy config locally
  copy:
    src: "{{ item.item }}"
    dest: "/home/{{ main_user }}/.config/autostart/{{ item.item | basename }}"
  with_dict:
    plasma_conf.results
  when:
    item.stat.exists == true

复制任务失败,返回fatal: [localhost] => with_dict expects a dict。如何基于dict提供的dict结构来实现这一点呢?在


Tags: name路径configshareusrconfwithitem
2条回答

感谢您的所有评论-debug和{}以前曾在多个迭代中使用过,但未能生成我想要的输出。我又回去了,用了久经考验的“废弃一切,从头开始”的方法,举了以下极简主义、自成体系的例子:

  -
 - hosts: 
    localhost
  tasks:
    - name: 
        create testing infrastructure a)
      file:
        path: "/tmp/{{ item }}"
        state: touch
        mode: 744
      with_items:
        - testFileA
        - testFileB
    - name: 
        create testing infrastructure b)
      file:
        path: "/tmp/testDir"
        state: directory
        mode: 744
    - name:
        identify files to act on
      stat:
        path: "{{ item }}"
      register:
        files2move
      with_items:
        - "/tmp/testFileA"
        - "/tmp/testFileB"
        - "/tmp/testFileC"
    - name:
        copy available files
      copy:
        src: "{{ item.item }}"
        dest: "/tmp/testDir/{{ item.item | basename }}"
        mode: 640
      with_items:
        files2move.results
      when:
        item.stat.exists == true

我真的不知道有什么不同,但这是有效的-无论是在最简版本还是移植回我的代码。。。在

plasma_conf.results是stat字典的列表。将第二个任务中的with_dict替换为with_items。请参见http://docs.ansible.com/ansible/playbooks_loops.html#using-register-with-a-loop,当然还有udondan建议的调试输出。在

相关问题 更多 >