-1

I have written this task that is supposed to go through a list of files and display the total amount of files located.

  - name: "Total File Count"
      shell: "kubectl exec pod/{{pod}} -- sh -c \"rclone size current-folder\""
      register: fileCount
      ignore_errors: True
    - debug: var=fileCount

it printout the following:

    "fileCount": {
        "changed": true,
        "cmd": "kubectl exec pod/files -- sh -c \"rclone size current-folder"",
        "delta": "0:12:43.170671",
        "end": "2021-09-29 18:04:47.206004",
        "failed": false,
        "rc": 0,
        "start": "2021-09-29 17:52:04.035333",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "Total objects: 867936\nTotal size: 6.730 TBytes (7400217383962 Bytes)",
        "stdout_lines": [
            "Total objects: 867936",
            "Total size: 6.730 TBytes (7400217383962 Bytes)"
        ]
    }
}

I want to get the total number of files/objects from the json output.

I have tried the following, but prints out the key and value "msg": "Total objects: 867936"

debug: msg="{{fileCount.stdout_lines[0]}}"

Is there a command I can retrieve that 867936 number?

Paul Blart
  • 183
  • 1
  • 3
  • 12
  • What have you tried, and what error is it producing for you? This is not a consultancy, it's to help you debug your own code. You will also want to make extensive use of the search feature while here, because this problem is not novel to your situation. – mdaniel Sep 30 '21 at 02:55
  • @mdaniel I understand, I thought there might be a better way to approach this scenario that I came across. If you want to look back on my OP you'll get the questions answered. Thanks for leaving a comment and I will use the search feature. – Paul Blart Sep 30 '21 at 05:01

1 Answers1

1

You should be able to use the regex_search filter extract the number.

For the first line, "Total objects: 867936" since there is only a single number in the line, we can simply do something like:

- debug:
    msg: "{{ fileCount.stdout_lines[0] | regex_search('[0-9]+') }}"
ok: [localhost] => {
    "msg": "867936"
}

If the string has multiple numbers in it, then it'll return the first result matching that regex. Suppose in the second line, "Total size: 6.730 TBytes (7400217383962 Bytes)", you wanted to extract the 7400217383962 number. Then we can utilize capture groups to specifically target the second number.

- debug:
    msg: "{{ fileCount.stdout_lines[1] | regex_search('([0-9]+) Bytes', '\\1') | first }}"
ok: [localhost] => {
    "msg": "7400217383962"
}
Rickkwa
  • 2,197
  • 4
  • 23
  • 34