-2

I am unable to read a list using shell module. It's working fo one element in list but fails for two or more elements.

tasks:
- name: Create a List variable and print it
  set_fact:
    UserRecords:

      [
    "[3/2/23 9:09:04:013 GMT+5:30] 0000 ApplicationMg A WSVR220I: Application stopped: ActivePackProdTest_war1",
     "[3/2/23 8:09:04:013 GMT+5:30] 0000 ApplicationMg A WSVR220I: Application stopped: ActivePackProdTest_war"
      ]


- name: split list
  shell: |

           for i in "{{ UserRecords }}"
           do
               echo $i||awk '{print $2,new_var=$8" "$9" "$10}'|sed 's/[^[:alnum:]:" "]//g'
           done

excepted output:

9:09:04:013 Application stopped: ActivePackProdTest_war1
8:09:04:013 Application stopped: ActivePackProdTest_war
Zeitounator
  • 38,476
  • 7
  • 53
  • 66
  • Wasn't the comment in [How can I get a limited output in JSON with Ansible](https://stackoverflow.com/questions/75332030/) that what you were looking for? – U880D Feb 03 '23 at 17:16
  • I added a debug task and it outputs the two lines including the date with [3/2/23 9:09:04:013 GMT+5:30]. Ansible 2.13.5 version. – ayuuk ja'ay Feb 03 '23 at 17:20
  • Although we know what is your expected output, we have no idea what currently fails and how. Please read [mre]. Moreover, using a shell task to loop over a list variable and echo a result is pure non sense. If this really what you want to do, use pure shell scripts without Ansible: it will be much easier. Else, it's time to learn Jinja2 (see as entry points https://jinja.palletsprojects.com/en/3.0.x/templates/ and https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_templating.html) – Zeitounator Feb 03 '23 at 21:52

1 Answers1

1

Try using Jinja2 to achieve the desired result. Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts. Hope this helps.

   ---
- hosts: 127.0.0.1
  gather_facts: false
  tasks:
  - name: Create a List variable and print it
    set_fact:
      UserRecords:
        [
          "[3/2/23 9:09:04:013 GMT+5:30] 0000 ApplicationMg A WSVR220I: Application stopped: ActivePackProdTest_war1",
          "[3/2/23 8:09:04:013 GMT+5:30] 0000 ApplicationMg A WSVR220I: Application stopped: ActivePackProdTest_war"
        ]
    delegate_to: 127.0.0.1

  - name: split list
    debug:
      msg: "{{ item.split(' ')[1] }} {{ item.split(':')[-2] }}:{{ item.split(':')[-1] }}"
    loop: "{{ UserRecords }}"
    delegate_to: 127.0.0.1

...