来自Ansible stdout_lines结果的过滤行

时间:2017-10-25 16:24:46

标签: linux filter grep ansible stdout

我正在尝试从Ansible stdout_lines结果中过滤掉一行。我运行的ansible playbook任务是以下shell参数:

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

要查看结果,我跟进了调试:

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

在playbook运行期间给出以下结果:

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

我只想要最后一个网址,“test_sqs”出现在“msg”下:,我尝试了以下过滤器,但没有运气:

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

2 个答案:

答案 0 :(得分:2)

aws cli默认生成JSON输出,使用此优势:

---
- 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 }}"

输出:

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

TASK [debug] **************************************
ok: [localhost] => {
    "msg": "https://eu-west-1.queue.amazonaws.com/xxxxx/test"
}

答案 1 :(得分:0)

<强>脚本:

---
- 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": [
        "https://queue.amazonaws.com/xxxxxxxxx/test_sqs-198O8HG46WK1Z"
    ]
}

您可以使用--queue-name-prefix参数仅列出以名称test_sqs开头的队列。如果只有一个具有该名称的队列,则可以使用此解决方案。