Dominik
Dominik

Reputation: 111

How to use AWK command via Ansible

I have a problem with creating ansible role.

I want to register variable via Ansible using awk in shell module.

It work when i use it via terminal like that:

inxi -D | awk '/Total Size:/ {print $7}' | cut -d"(" -f2

But when I want to use it in Ansible role it doesnt work.

name: Get info
shell: inxi -D | awk '/Total Size:/ {print $7}' | cut -d"(" -f2
register: result

Displayed info from inxi -D is

Drives:    HDD Total Size: 53.7GB (2.0% used)
           ID-1: /dev/vda model: N/A size: 53.7GB
           ID-2: /dev/vdb model: N/A size: 0.0GB

And I want to extract data about usage fo HDD e.g. 2.0%

Can someone help with that?

Upvotes: 4

Views: 26881

Answers (5)

valentin blondeau
valentin blondeau

Reputation: 1

we just find a stupid workaround that work:

echo $(df -h /hadoop | awk 'NR==2 {print $4}') 

for the first case :

      tasks:
      - name: test shell
        shell: echo $(inxi -D | awk '/Total Size:/ {print $7}' | cut -d"(" -f2)
        register: result

Upvotes: 0

Lizardx
Lizardx

Reputation: 1195

inxi as of version 3.0 exports to json or xml:

inxi -Dxxx --output json --output-file print

'print' is print to stdout, if a full file path is given, it exports to the file.

Upvotes: 0

Dominik
Dominik

Reputation: 111

This way it works fine

 - name: Get informations about disk percentage
      shell: >
                inxi -D |
                grep 'Total'|
                sed -e 's/.*(\(.*\)\ .*/\1/'
      register: result

- debug:
      msg: "{{ result.stdout }}"

Upvotes: 2

nbari
nbari

Reputation: 26955

Give a try to this:

---
- hosts: localhost
  connection: local

  tasks:
  - name: test shell
    shell: >
      echo "Drives:    HDD Total Size: 53.7GB (2.0% used)" | awk -F '[()]' '/Total Size:/ {split($2,a," "); print a[1]}'
    register: result

  - debug:
      msg: "{{ result.stdout }}"

It should print something like:

"msg": "2.0%"

If working then just replace the echo ... with your command: inxi -D | awk ...

Notice the shell: >

In yaml, Multiple-line strings can be written either as a 'literal block' (using |), or a 'folded block' (using >).

Also changed the use of awk to use all in one by using [()] as the separator, this will get contents within parentheses.

Upvotes: 3

user5777975
user5777975

Reputation:

Try to execute as below:

 name: Get info
 shell: inxi -D | awk '/Total Size:/ {print $7}' | cut -d"(" -f2
 register: result

and access the output of that command by "{{ result.stdout }}"

Upvotes: 0

Related Questions