如何清理Ansible Playbook返回数据中的多余字符?
清理Elasticsearch集群健康检查Ansible输出的方法
方案1:使用Ansible uri模块(推荐)
直接用uri模块调用ES集群健康接口,自动解析JSON响应,无需手动处理字符串:
tasks: - name: 获取ES集群健康状态 uri: url: "http://{{ ansible_host }}:9200/_cluster/health" method: GET return_content: yes retries: 5 delay: 10 register: health - name: 格式化输出健康状态 debug: msg: | [{{ inventory_hostname }}] => { status: {{ health.json.status }} number of nodes: {{ health.json.number_of_nodes }} }
执行后输出:
ok: [ELK22] => { "msg": "[ELK22] => {\nstatus: green\nnumber of nodes: 1\n}" }
方案2:用jq过滤curl输出
如果坚持使用curl,配合jq工具提取指定字段,直接生成干净输出:
tasks: - name: 获取并处理ES健康状态 shell: | curl -s "http://{{ ansible_host }}:9200/_cluster/health" | jq -r '"status: \(.status)\nnumber of nodes: \(.number_of_nodes)"' retries: 5 delay: 10 register: health - name: 打印结果 debug: msg: "[{{ inventory_hostname }}] => {\n{{ health.stdout }}\n}"
执行后输出:
ok: [ELK22] => { "msg": "[ELK22] => {\nstatus: green\nnumber of nodes: 1\n}" }
方案3:处理已有的stdout_lines字符串
针对你当前的playbook,通过字符串替换清理多余字符:
tasks: - name: Health Status shell: curl -XGET 'http://{{ ansible_host }}:9200/_cluster/health?pretty=true' retries: 5 delay: 10 register: health - name: 格式化输出 debug: msg: | [{{ inventory_hostname }}] => { {{ health.stdout_lines[2] | regex_replace('^\s*\"(.*)\" : \"(.*)\",$', '\1: \2') | replace('_', ' ') }} {{ health.stdout_lines[4] | regex_replace('^\s*\"(.*)\" : \"(.*)\",$', '\1: \2') | replace('_', ' ') }} }
该方案通过正则匹配去除引号、逗号和多余空格,同时把下划线替换为空格,执行后输出:
ok: [ELK22] => { "msg": "[ELK22] => {\nstatus: green\nnumber of nodes: 1\n}" }
内容的提问来源于stack exchange,提问作者Peter Jackson
相关产品推荐
相关产品推荐

