【问题标题】:Translate command output to dictionary in specific case在特定情况下将命令输出转换为字典
【发布时间】:2019-01-22 19:20:17
【问题描述】:

我在 ansible 角色中有以下任务:

- name: get answer from server
  command: "curl http://my_server:8888" 
  register: response

现在,response.stdout 看起来完全像:

Server: 10.8.7.1
Domain: com
State: Health
Type: B

Server: 10.8.7.2
Domain: eu
State: Health
Type: A

Server: 10.8.7.3
Domain: com
State: Health
Type: C

Server: 10.8.7.4
Domain: com
State: Bad
Type: C

如何将其翻译成字典列表(如{"Server": "10.8.7.1", "Domain": "com","State": "Health","Type": "B"})?

我考虑编写自己的 python 模块,但是我相信您可以知道一些更优雅的方式。

【问题讨论】:

标签: ansible


【解决方案1】:

不知道优雅,但如果 curl 的输出稳定且可预测,您可以这样做:

- name: get answer from server
  shell: curl http://my_server:8888 | sed -e 's/^/  /' -e 's/  Server/- Server/'
  register: response
- debug:
    var: response.stdout | from_yaml
  • 注意因为是引入管道,需要从comannd切换到shell
  • 我们正在使用sed 命令将输出格式化为类似于 YAML 的格式
  • 因此,我们可以将response.stdout 传递给from_yaml 过滤器,它会将字符串解码为字典列表

再次,不确定优雅。对我来说感觉有点脏,但是,嘿,完成工作:)

至于干净的方法——如果可能的话,在远程服务器上获取以某种结构化格式(最好是 JSON)生成的文件,然后你可以使用 Ansible uri 模块来读取它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2019-10-28
    • 1970-01-01
    • 2014-06-13
    相关资源
    最近更新 更多