Techie
Techie

Reputation: 25

Print available disk space and send email notification

I have a playbook to check the hard drive free space and send email if the threshold limit is reached. Following is my play

---
- hosts: Test
  tasks:
    - name: Ensuring that free space on '/' is grater than 30%
      assert:
    that:
          - not {{ item.mount == '/' and ( item.size_available < item.size_total - ( item.size_total|float * 0.3 ) ) }}
      with_items: '{{ ansible_mounts }}'
      ignore_errors: yes
      register: disk_free
    -  debug: var=disk_free

    - name: Notifying the IT admin about the disk usage
      mail:
    host="smtp.myserver.com"
        port="2525"
        username="my_username"
        password="my_password"
        from="my_email"
        to="to_email"
        subject='HDD Space Low'
        body='{{ inventory_hostname }} is running low on disk space. Currently {{ disk_free.results['item']['size_available'] }}MB available.'

Following is the debug output I receive when i run the above play:

ok: [Test] => {
    "disk_free": {
        "changed": false, 
        "failed": true, 
        "msg": "One or more items failed", 
        "results": [
            {
                "_ansible_item_result": true, 
                "_ansible_no_log": false, 
                "_ansible_verbose_always": true, 
                "assertion": "not True", 
                "evaluated_to": false, 
                "failed": true, 
                "item": {
                    "device": "/dev/mapper/centos-root", 
                    "fstype": "xfs", 
                    "mount": "/", 
                    "options": "rw,seclabel,relatime,attr2,inode64,noquota", 
                    "size_available": 18377105408, 
                    "size_total": 19828572160, 
                    "uuid": "d700725b-6937-4e56-8e20-2039e787f055"
                }

Now, when I access the result veriable within the notification email body, it fails.

FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute

So can somebody please help me to print the 'size_available' value within the outgoing email?

Upvotes: 1

Views: 5425

Answers (1)

techraf
techraf

Reputation: 68469

You get:

'list object' has no attribute

If you look at the result of your debug task, you'll notice disk_free.results is a list (because you used a loop when registering), so it does not contain item.

For a single value you might refer to disk_free.results[0]['item']['size_available'], but I guess you should iterate over the list.

Upvotes: 1

Related Questions