How to use AWK command via Ansible
17,352
Solution 1
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 }}"
Solution 2
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.
Related videos on Youtube
Author by
Dominik
Updated on June 04, 2022Comments
-
Dominik almost 2 years
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
isDrives: 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?
-
Admin almost 6 yearswhat output you got for
inxi -D | awk '/Total Size:/ {print $7}' | cut -d"(" -f2
? -
Dominik almost 6 years2.0% from line
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 ` -
ghoti almost 6 yearsCan you add the output of just
inxi -D
to your question, so that it (1) retains proper formatting and (2) allows us to suggest a better way to do this? -
tripleee almost 6 years
-
Dominik almost 6 years@ghoti I have add info
-
Paul Samsotha almost 3 yearsNot sure if this is the same problem, but I was trying to run a
shell
command and I just had to escape the\$
.
-
-
Dominik almost 6 yearsI have tried that and it doesnt work.
changed: [168.99.241.225] => {"changed": true, "cmd": "inxi -D | awk '/Total Size:/ {print $7}' | cut -d\"(\" -f2", "delta": "0:00:00.197516", "end": "2018-05-20 17:38:12.433230", "rc": 0, "start": "2018-05-20 17:38:12.235714", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
-
ghoti almost 6 yearsThat
grep
is entirely unnecessary; the same filtering can be done in sed alone. What about justinxi -D | sed -ne '/^Drives/{s/.*(//;s/ .*//;p;q;}'
?