user11549576
user11549576

Reputation: 159

how to extract string from ansible regsiter variable in ansible

I have written the following ansible playbook to find the disk failure on the raid

- name: checking raid status
  shell: "cat /proc/mdstat | grep nvme"
  register: "array_check"
- debug:
    msg: "{{ array_check.stdout_lines }}"

Following is the output I got

"msg": [
    "md0 : active raid1 nvme0n1p1[0] nvme1n1p1[1]", 
    "md2 : active raid1 nvme1n1p3[1](F) nvme0n1p3[0]", 
    "md1 : active raid1 nvme1n1p2[1] nvme0n1p2[0]"
]

I want to extract the disk name which is failed from the register variable array_check.

How do I do this in the ansible? Can I use set_fact module in ansible? Can I use grep, awk, sed command on the register variable array_check


This is the playbook I am using to check the health status of a drive using smartctl

- name: checking the smartctl logs
shell: "smartctl -H /dev/{{ item }}"
with_items:
        - nvme0
        - nvme1  

And I am facing the following error

(item=nvme0) => {"changed": true, "cmd": "smartctl -H /dev/nvme0", "delta": "0:00:00.090760", "end": "2019-09-05 11:21:17.035173", "failed": true, "item": "nvme0", "rc": 127, "start": "2019-09-05 11:21:16.944413", "stderr": "/bin/sh: 1: smartctl: not found", "stdout": "", "stdout_lines": [], "warnings": []}

(item=nvme1) => {"changed": true, "cmd": "smartctl -H /dev/nvme1", "delta": "0:00:00.086596", "end": "2019-09-05 11:21:17.654036", "failed": true, "item": "nvme1", "rc": 127, "start": "2019-09-05 11:21:17.567440", "stderr": "/bin/sh: 1: smartctl: not found", "stdout": "", "stdout_lines": [], "warnings": []}

The desired output should be something like this,

=== START OF SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

Upvotes: 0

Views: 2609

Answers (1)

Shubham Vaishnav
Shubham Vaishnav

Reputation: 1720

Below is the complete playbook including the logic to execute multiple commands in a single task using with_items,

--- 
 - hosts: raid_host
   remote_user: ansible
   become: yes
   become_method: sudo 
   tasks: 
     - name: checking raid status 
       shell: "cat /proc/mdstat | grep 'F' | cut -d' ' -f6 | cut -d'[' -f1" 
       register: "array_check"

     - debug:
        msg: "{{ array_check.stdout_lines }}"

     - name: checking the samrtctl logs for the drive 
       shell: "/usr/sbin/smartctl -H /dev/{{ item }} | tail -2|awk -F' ' '{print $6}'"
       with_items:
         - "nvme0"
         - "nvme1"
       register: "smartctl_status"

Upvotes: 1

Related Questions