Fetch the values of the variables in ansible

Viewed 46

I am trying to list the names whose matches have been found.

- name: search for files containing string
 find:
   paths: /root/ansible-dir
   patterns: "file3.yml"
   contains: "{{ item }}"
 with_items: "{{ names_list }}"
 register: file_match

- name: print file
  debug:
    msg: "{{ file_match }}"

After the above code is run, the below code gets generated :

    "msg": {
        "changed": false,
        "msg": "All items completed",
        "results": [
            {
                "ansible_loop_var": "item",
                "changed": false,
                "examined": 14,
                "failed": false,
                "files": [],
                "invocation": {
                    "module_args": {
                        "age": null,
                        "age_stamp": "mtime",
                        "contains": "node_mem",
                        "depth": null,
                        "excludes": null,
                        "file_type": "file",
                        "follow": false,
                        "get_checksum": false,
                        "hidden": false,
                        "paths": [
                            "/root/ansible-dir"
                        ],
                        "patterns": [
                            "file3.yml"
                        ],
                        "recurse": false,
                        "size": null,
                        "use_regex": false
                    }
                },
                "item": "node_mem",
                "matched": 0,
                "msg": ""
            },

How to fetch the name of the item where the matched attribute is >=1?

1 Answers

Use subelements. The debug below gives you a hint how to iterate the results and fetch files that contain the items

    - debug:
        msg: "Fetch {{ item.1 }}"
      with_subelements:
        - "{{ file_match.results }}"
        - files

It is not necessary to test the number of files is >=1. If the list of files is empty the iteration will be skipped anyway.

Related