Home > Software design >  How to grep/parse in string with Ansible
How to grep/parse in string with Ansible

Time:07-16

I have problem with ansible. I need get version of apache with ansible, and I'm using command "httpd -v" in /bin/ folder of apache. Now, I've got output looks like "Server version: Apache/2.4.48 (Win64) Apache Lounge VS16 Server built: May 18 2021 10:45:56". So, can you help me please? I tried to use "regex" and there was still error.

CodePudding user response:

Register the result of the command

    - command: httpd -v
      register: result

gives, for example,

result.stdout: |-
  Server version: Apache/2.4.46 (FreeBSD)
  Server built:   unknown

This is actually a YAML dictionary. Let's keep it in a variable. For example,

apache: "{{ result.stdout|from_yaml }}"

gives

apache:
  Server built: unknown
  Server version: Apache/2.4.46 (FreeBSD)

Now, you can reference the attributes. For example,

apache['Server version']: Apache/2.4.46 (FreeBSD)

and split the version

apache_version: "{{ apache['Server version']|split(' ')|first|
                                             split('/')|last }}"

gives

apache_version: 2.4.46

Example of a complete playbook

- hosts: srv
  vars:
    apache: "{{ result.stdout|from_yaml }}"
    apache_version: "{{ apache['Server version']|split(' ')|first|
                                                 split('/')|last }}"
  tasks:
    - command: httpd -v
      register: result
    - debug:
        var: apache_version

CodePudding user response:

using regex_search:

---
- hosts: localhost
  tasks:

  - name: Run httpd command
    shell: httpd -v
    register: httpd_version

  - name: show the extracted output
    debug:
      msg: "{{ httpd_version.stdout |regex_search('Server version.*?/([^ ] ).*','\\1') }}"
  • Related