Reputation: 127
I am trying to write some automation using Ansible and I've come across a situation where I need to use multiple parts of a command output in a task later down the playbook.
I have a task that is going to run the command "lspci | grep Ethernet | grep Gigabit"
The output should look something like this (should be 2 lines of output):
"02:00.0 Ethernet controller: Intel Corporation 82575EB Gigabit Network Connection (rev 02)"
"02:00.1 Ethernet controller: Intel Corporation 82575EB Gigabit Network Connection (rev 02)
Out of this output, I need to extract 4 pieces of information as variables.
var1 - I want the bus of the first line. Should be "02"
var2 - I want the function of the first line. Should be "0"
var3 - I want the bus of the second line. Should be "02"
var4 - I want the function of the second line. Should be "1"
How do I go about extracting the information from the output into these 4 variables? Doesn't necessarily have to be a single play that gets all 4 variables.
Thanks for the help.
Upvotes: 3
Views: 8029
Reputation: 12913
As suggested, you should register
the output of the command. After that, you can loop over the results and grab the parts you're interested in.
Working example:
- name: Fun with lspci output
hosts: localhost
connection: local
tasks:
- name: get Gigabit Ethernet adapters
shell: lspci | grep Ethernet | grep Gigabit | awk '{print $1}'
register: eth_adapters
- name: use extracted info
debug: msg="Adapter found, bus {{item.split(':')[0]}}, function {{item.split('.')[-1]}}"
with_items: "{{eth_adapters.stdout_lines}}"
Note the use of eth_adapters.stdout_lines
to get the command output as a list of items, and the awk '{print $1}'
to only grab the bus info of the devices.
This example produces the following output:
PLAY [Fun with lspci output] ***************************************************
TASK [setup] *******************************************************************
ok: [localhost]
TASK [get Gigabit Ethernet adapters] *******************************************
changed: [localhost]
TASK [use extracted info] ******************************************************
ok: [localhost] => (item=00:00.0) => {
"item": "00:00.0",
"msg": "Adapter found, bus 00, function 0"
}
ok: [localhost] => (item=00:01.0) => {
"item": "00:01.0",
"msg": "Adapter found, bus 00, function 0"
}
ok: [localhost] => (item=00:01.1) => {
"item": "00:01.1",
"msg": "Adapter found, bus 00, function 1"
}
ok: [localhost] => (item=00:01.3) => {
"item": "00:01.3",
"msg": "Adapter found, bus 00, function 3"
}
PLAY RECAP *********************************************************************
localhost : ok=3 changed=1 unreachable=0 failed=0
Upvotes: 8