Search code examples
selectansiblestdoutstderr

Extracting specific value from stderr_lines


This is my ansible script

- name: show1
  debug:
    msg: "{{response.stderr_lines}}"

Here is the output

msg:
      - Using endpoint [https://us-central1-aiplatform.googleapis.com/]
      - CustomJob [projects/123456/locations/us-central1/customJobs/112233445566] is submitted successfully.
      - ''
      - Your job is still active. You may view the status of your job with the command
      - ''
      - '  $ gcloud ai custom-jobs describe projects/123456/locations/us-central1/customJobs/112233445566'
      - ''
      - or continue streaming the logs with the command
      - ''
      - '  $ gcloud ai custom-jobs stream-logs projects/123456/locations/us-central1/customJobs/112233445566'

Here I want to extract custom Job ID which is 112233445566

I used the select module like below

- name: show
  debug:
    msg: "{{train_custom_image_unmanaged_response.stderr_lines | select('search', 'describe') | list }}"

and it gives me this output

msg:
  - '  $ gcloud ai custom-jobs describe projects/123456/locations/us-central1/customJobs/112233445566'

But I just want the job id as specified above. Any idea about that ?

Thanks.


Solution

  • You selected the line you are interested in. From that now you want to isolate the job id number in the end. You can do that using a regular expression like so:

    - set_fact:
        line: "{{train_custom_image_unmanaged_response.stderr_lines | select('search', 'describe') | list }}"
    - debug:
        msg: "{{ line | regex_search('.*/customJobs/(\\d+)', '\\1') }}"
    

    This will give you all the digits in the end of the line after /customJobs/. See https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#searching-strings-with-regular-expressions