【问题标题】:How to extract the exact output from stdout.lines in ansible如何在ansible中从stdout.lines中提取准确的输出
【发布时间】:2018-12-19 08:10:18
【问题描述】:

我的 Ansible 剧本:

#Tag --> B.6 -->
  - name: Change the Security Realm to CustomRealm from ManagementRealm
command: /jboss-as-7.1.1.Final/bin/jboss-cli.sh --connect--command="/core-service=management/management-interface=http-interface:read-attribute(name=security-realm)"
register: Realm

  - debug:
  msg: "{{ Realm.stdout_lines }}"

消息中上述命令的输出如下:

ok: [342f2f7bed8e] => {
"msg": [
"{",
"    \"outcome\" => \"success\","
"    \"result\" => \"ManagementRealm\"",
"}"
]
}

有没有办法精确的“结果”=>“管理领域”。 我尝试使用

Realm.stdout_lines.find('result')

但是失败了,AWk 和 grep 命令似乎在这里不起作用。

非常感谢任何想法。

谢谢

【问题讨论】:

    标签: ansible ansible-2.x ansible-facts ansible-template


    【解决方案1】:

    我认为有几种方法可以解决这个问题。

    1) 在输出到 Ansible 之前对输出进行 Grep:

    # Note the change of 'command' to 'shell'
    - name: Change the Security Realm to CustomRealm from ManagementRealm
      shell: /jboss-as-7.1.1.Final/bin/jboss-cli.sh --connect--command="/core-service=management/management-interface=http-interface:read-attribute(name=security-realm)" | grep -o 'result.*'
      register: Realm
    

    2) 如果源脚本的输出总是 4 行长,你可以抓住第 3 行:

    # List indexes start at 0
    - debug:
      msg: "{{ Realm.stdout_lines[2] | regex_replace('^ *(.*$)', '\\1') }}"
    

    3) 如果您有修改 jboss-cli.sh 的选项,最好的方法是让 jboss-cli.sh 输出有效的 JSON,然后可以由 Ansible 解析:

    # Assuming jboss-cli.sh produces {"outcome": "success", "result": "ManagementRealm"}
    - set_fact:
        jboss_data: "{{ Realm.stdout | from_json }}"
    - debug:
        var: jboss_data.result
    

    【讨论】:

    • (1) 如果您实际上使用 shell 执行任务并且必须使用 grep,那么使用 ansible 有什么意义? (2)如果您必须知道哪个行号对您感兴趣,并且当这个假设不正确时您无法有效地做出反应,那么使用自动化工具有什么意义? (3) 如果像过滤字符串这样的基本简单任务需要启动 json 分析机器,那么使用 ansible 有什么意义?它提醒我将结果放入 MS SQL 企业版中以进行简单选择。也许这是第四个选项?
    • 大声笑。 (1)添加详细评论意味着所提供的答案不够好,而不自己提供“正确”答案有什么意义? (2) 没有发现过滤字符串的任务与自动化过滤字符串的任务完全不同,可能只是大量相关任务中的一个步骤,这有什么意义?想必你知道 Ansible 在很大程度上只是通过 SSH 自动运行 shell 脚本和命令,尽管它包装在一大块 Python 中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多