Louis Smith
Louis Smith

Reputation: 71

How to put file paths into variable in ansible?

I'm trying to filter paths from a file to a variable from a dictionary the paths file: paths.yml

---

 files:
         - {path: /root/files_to_copy/file_1}

 files:
         - {path: /root/files_to_copy/file_2}
         - {path: /root/files_to_copy/file_3}
         - {path: /root/files_to_copy/file_4}

 files:
         - {path: /root/files_to_copy/file_5}
         - {path: /root/files_to_copy/file_6 }
         - {path: /root/files_to_copy/file_7 }

what my main.yml: why I can't use paths.values().path ?? or split ??

    - name: putting paths into a variable
      include_vars:
        file: paths.yml
        name: paths
    - debug: 
        msg: "{{ paths.values() }}"


result: 
   ok: [192.168.1.10] => {
        "msg": [
           [
                {
                    "path": "/root/files_to_copy/file_2"
                },
                {
                    "path": "/root/files_to_copy/file_3"
                },
                {
                    "path": "/root/files_to_copy/file_4"
                }
            ],

I want the output something like this: /root/files_to_copy/file_2, without path and braces

Upvotes: 0

Views: 559

Answers (1)

Moon
Moon

Reputation: 3037

When you have loaded paths.yml file with name paths, it loaded the whole file in a variable paths and the values are all the key value pair from paths.yml file.

To extract only the final path there are multiple options. Here is a sample:

    - debug: 
        msg: "{{ paths.values() | flatten | map(attribute='path') | list }}"

gives

ok: [localhost] => 
  msg:
  - /root/files_to_copy/file_1
  - /root/files_to_copy/file_2
  - /root/files_to_copy/file_3
  - /root/files_to_copy/file_4
  - /root/files_to_copy/file_5
  - /root/files_to_copy/file_6
  - /root/files_to_copy/file_7

Alternative and probably simpler, using json_query filter.

    - debug: 
        msg: "{{ paths | json_query('*[].path') | list }}"

Upvotes: 1

Related Questions