Haf*_*fiz 6 json uri ansible sonarqube ansible-playbook
我有一个服务调用,以json
格式返回系统状态.我想使用ansible URI模块进行调用,然后检查响应以确定系统是启动还是关闭
{"id":"20161024140306","version":"5.6.1","status":"UP"}
Run Code Online (Sandbox Code Playgroud)
这将json
是返回的
这是发出呼叫的安全任务:
- name: check sonar web is up
uri:
url: http://sonarhost:9000/sonar/api/system/status
method: GET
return_content: yes
status_code: 200
body_format: json
register: data
Run Code Online (Sandbox Code Playgroud)
问题是如何data
根据ansible文档访问和检查它,这是我们存储呼叫结果的方式.我不确定检查状态的最后一步.
Haf*_*fiz 20
这适合我.
- name: check sonar web is up
uri:
url: http://sonarhost:9000/sonar/api/system/status
method: GET
return_content: yes
status_code: 200
body_format: json
register: result
until: result.json.status == "UP"
retries: 10
delay: 30
Run Code Online (Sandbox Code Playgroud)
请注意,这result
是一个ansible字典,当您设置return_content=yes
响应时,会将响应添加到此字典中,并且可以使用json
键访问
还要确保正确缩进任务,如上所示.
通过将输出保存到变量,您已经迈出了正确的第一步。
下一步是在下一个任务中使用when:
或failed_when:
语句,然后将根据变量的内容进行切换。在这些过滤器中,有一整套强大的语句可以使用,即Jinja2内置过滤器,但它们与Ansible文档之间的链接并不紧密,也没有很好地概括。
我使用了超级显式命名的输出变量,因此稍后在剧本中对我来说是有意义的:)我可能会写出类似以下内容的变量:
- name: check sonar web is up
uri:
url: http://sonarhost:9000/sonar/api/system/status
method: GET
return_content: yes
status_code: 200
body_format: json
register: sonar_web_api_status_output
- name: do this thing if it is NOT up
shell: echo "OMG it's not working!"
when: sonar_web_api_status_output.stdout.find('UP') == -1
Run Code Online (Sandbox Code Playgroud)
也就是说,在变量的标准输出中找不到文本“ UP”。
我使用过的其他Jinja2内置过滤器是:
changed_when: "'<some text>' not in your_variable_name.stderr"
when: some_number_of_files_changed.stdout|int > 0
该Ansible“条件”文档页面有一些这个信息的。这篇博客文章也非常有用。
根据https://docs.ansible.com/ansible/latest/modules/uri_module.html上的文档
是否将响应正文作为字典结果中的“内容”键返回。与此选项无关,如果报告的 Content-type 是“application/json”,则 JSON 始终加载到字典结果中名为 json 的键中。
---
- name: Example of JSON body parsing with uri module
connection: local
gather_facts: true
hosts: localhost
tasks:
- name: Example of JSON body parsing with uri module
uri:
url: https://jsonplaceholder.typicode.com/users
method: GET
return_content: yes
status_code: 200
body_format: json
register: data
# failed_when: <optional condition based on JSON returned content>
- name: Print returned json dictionary
debug:
var: data.json
- name: Print certain element
debug:
var: data.json[0].address.city
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18822 次 |
最近记录: |