Ansible yum update then email me the results

ansibleemailgrepyum

Writing a playbook to perform yum updates and then get an email from each server. I'd like the email to contain the changed contents of yum.log.

IOW, I want the results of:

grep [today's date] /var/log/yum.log

to be emailed from each server.

I tried using shell: to perform the grep then send the mail :

    shell: grep '^`date +"%b %d"`' /var/log/yum.log | mail -s "updates applied to `hostname -s` today" updatereports@mydomain.com

It just sends a blank email.

Also tried using the mail function but am struggling to dump a multi-line variable into the body of the message:

- name: test result
  ignore_errors: yes
  shell: grep "`date '+%b %d'`" /var/log/messages
  register: updated

- name: mail result
  mail:
    to: updatereports@mydomain.com
    subject: "updates applied to {{ ansible_hostname }} today"
    body: "{{ item }}"
    with_items: "{{ updated.results|map(attribute='stdout_lines')|list }}"
  when: updated.stdout

It also sends, but prints the timestamp then generates a line of errors for each matched line in yum.log:

['Sep 12 16:15:28 host-ng ansible-command: Invoked with warn=True executable=None _uses_shell=True _raw_params=grep "`date \'+%b %d\'`" /var/log/messages | tail removes=None creates=None chdir=None'

I found that fancy results|map code here but don't understand it enough to work without errors.

Best Answer

I am not certain if it is your only problem, but one problem is that your with_items is indented incorrectly. The with_items belongs to a task, not the mail.

- name: mail result
  mail:
    to: updatereports@mydomain.com
    subject: "updates applied to {{ ansible_hostname }} today"
    body: "{{ item }}"
  with_items: "{{ updated.results|map(attribute='stdout_lines')|list }}"
  when: updated.stdout

I am not really sure if you need the with_items at all in this case though. You need to use with_items when you are looping over a collection of something.

Since I don't know the answer, if I where in your shoes I would simply start with some simple debug tasks instead of the mail. Once you see the results of the debug it should be a lot easier to see what you need to do.

- name: mail result
  debug:
    msg: "{{ updated }}"
- name: mail result
  debug:
    msg: ""{{ updated.results|map(attribute='stdout_lines')|list }}""
Related Topic