J. *_*ary 5 linux grep stdout filter ansible
我正在尝试从 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
Run Code Online (Sandbox Code Playgroud)
为了查看结果,我进行了调试:
- debug:
msg: "{{ sqs_list.stdout_lines|list }}"
Run Code Online (Sandbox Code Playgroud)
在剧本运行期间给出以下结果:
TASK [sqs : debug] ********************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
"{",
" \"QueueUrls\": [",
" \"sampleurl1\",",
" \"sampleurl2\",",
" \"sampleurl3\",",
" \"sampleurl4\",",
" \"https://sampleurl5/test_sqs\"",
" ]",
"}"
]
}
Run Code Online (Sandbox Code Playgroud)
我只希望最后一个 url,“test_sqs”出现在“msg”: 下,我尝试了以下过滤器,但没有运气:
- name: VERIFY | Find SQS url
command: "{{ sqs_list.stdout_lines|list }} -- formats | grep $sqs"
Run Code Online (Sandbox Code Playgroud)
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 }}"
Run Code Online (Sandbox Code Playgroud)
输出:
PLAY [localhost] **********************************
TASK [command] ************************************
changed: [localhost]
TASK [debug] **************************************
ok: [localhost] => {
"msg": "https://eu-west-1.queue.amazonaws.com/xxxxx/test"
}
Run Code Online (Sandbox Code Playgroud)
脚本:
---
- 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 }}"
Run Code Online (Sandbox Code Playgroud)
Output:
ok: [localhost] => {
"msg": [
"https://queue.amazonaws.com/xxxxxxxxx/test_sqs-198O8HG46WK1Z"
]
}
Run Code Online (Sandbox Code Playgroud)
您可以使用该--queue-name-prefix参数仅列出以 name 开头的队列test_sqs。如果只有一个具有该名称的队列,则可以使用此解决方案。