How to extract the exact output from stdout.lines in ansible

anish anil picture anish anil · Dec 19, 2018 · Viewed 8.7k times · Source

My Ansible Playbook:

#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 }}"

The output for the above command in the message is as follows:

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

is there a way to just exact \"result\" => \"ManagementRealm\"". I tried using the

Realm.stdout_lines.find('result')

but that fails, AWk & grep commands doesn't seem to be working here.

Any thoughts is greatly appreciated.

Thak you

Answer

clockworknet picture clockworknet · Dec 19, 2018

I think there are a few ways you could handle this.

1) Grep the output before it gets to Ansible:

# 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) If the output from the source script is always 4 lines long, you can just grab the 3rd line:

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

3) The nicest way if you have an option to modify jboss-cli.sh, would be to get the jboss-cli.sh to output valid JSON which can then be parsed by Ansible:

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