代码之家  ›  专栏  ›  技术社区  ›  Risha

Ansible:如何用项目替换字符串中的文本

  •  2
  • Risha  · 技术社区  · 7 年前

    我有一个Ansible命令,它返回一个目录列表:

    - local_action: command find {{ role_path }}/files -type f
      register: result
    

    例如,它返回了两条路径: path/files/a/1.zip path/files/a/2.zip /a/1.zip /a/2.zip 并注册删除这些文件的结果。我试过了 regex_replace 和shell with sed

      - command: "echo {{item}} | sed s/'{{ role_path }}/files'/''"
        with_items: "{{result.stdout_lines}}"
        register: script_results
    
      - msg: {{ item | regex_replace('/path/files','\\1') }}
        with_items: "{{result.stdout_lines}}"
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Piotr Babij    7 年前

    如注释中所述:首先不应使用命令。您可以委托 find 任务到 127.0.0.1

    您可以使用 the relpath filter 要删除路径的开头,可以使用 map 过滤器 attribute 为了方便地提取路径:

    - find:
        path: "{{ role_path }}"
        recurse: yes
      register: result
      delegate_to: 127.0.0.1
    
    - debug:
        msg: "{{ item | relpath(role_path) }}"
      with_items: "{{ result.files | map(attribute='path')}}"
    

    ok: [127.0.0.1] => (item=/path/to/role/dir/file_1) => {
        "item": "/path/to/role/dir/file_1", 
        "msg": "dir/file_1"
    }