Filter Line from Ansible Stdout_Lines Result

I am trying to filter out a line out of Ansible stdout_lines result. The ansible playbook task I ran was the following shell argument:

- name: VERIFY | Confirm that queue exists properly
  shell: aws sqs list-queues --region {{region}}
  environment: "{{ aws_cli_environment|d({}) }}"
  register: sqs_list

To see the results, I followed it up with a debug:

- debug:
    msg: "{{ sqs_list.stdout_lines|list }}"

which gives the following result during the playbook run:

TASK [sqs : debug] ********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "{",
        "    \"QueueUrls\": [",
        "        \"sampleurl1\",",
        "        \"sampleurl2\",",
        "        \"sampleurl3\",",
        "        \"sampleurl4\",",
        "        \""",
        "    ]",
        "}"
    ]
}

I want ONLY the last url, "test_sqs" to appear under "msg":, I tried the following filter but had no luck:

- name: VERIFY | Find SQS url
  command: "{{ sqs_list.stdout_lines|list }} -- formats | grep $sqs"

2 Answers

aws cli generates JSON output by default, use this advantage:

---
- hosts: localhost
  gather_facts: no
  tasks:
    - shell: aws sqs list-queues --region eu-west-1
      register: sqs_list
    - debug:
        msg: "{{ (sqs_list.stdout | from_json).QueueUrls | last }}"

Output:

PLAY [localhost] **********************************
TASK [command] ************************************
changed: [localhost]

TASK [debug] **************************************
ok: [localhost] => {
    "msg": ""
}
2

Script:

---
- name: A simple template
  hosts: local
  connection: local
  gather_facts: False
  tasks:
    - name: list queue
      shell: aws sqs list-queues --region us-east-1 --queue-name-prefix test_sqs --query 'QueueUrls[*]' --output text
      register: sqs_list
    - debug: 
        msg: "{{ sqs_list.stdout_lines|list }}"

Output:

ok: [localhost] => {
    "msg": [
        ""
    ]
}

You can make use of the --queue-name-prefix parameter to list only queues which is starting with name test_sqs. If there is only one queue with that name, you can use this solution.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest