Ansible: loops and registering results of commands

Ansible has a great feature of registering results of a performed step. But recently I stumbled upon a need to do it against actions from a loop and then using the registered result in the next steps which are also looped. Most often, it can be used to perform some action only in case if a previous action changed a file.

Firstly, we register `action_state` variable. Its sub-dictionary `results` contains attribute `changed` which can be accessed as `action_state.results.changed`. Now, we need to get it into use in the next looped step. It can be done with ease using `with_together` operator:

- name: copy a file
  copy:
    src: '{{ source }}'
    dest: '{{ target }}'
  with_items: yourlist
  when: item.state == 'present'
  register: action_state

- name: create .ssh dir if file changed in the previous step
  sudo_user: '{{ item.0.user }}'
  file:
    state: directory
    path: '/home/{{ item.0.user }}/.ssh'
    mode: 0700
  with_together:
  - yourlist
  - action_state.results
  when: item.1.changed and item.0.state == 'present'

Here, for the `yourlist` we copied some files to a target machine (i.e. public keys to some temp location) in the loop and then for each of the files performed an action only if a file was changed.

Books for getting more power with PowerShell

When you look at available PowerShell books, almost every link at the Internet points you to the infamous:

Jones, Don, and Jeffrey T. Hicks. Learn Windows PowerShell 3 in a Month of Lunches. Manning, 2013.

This book is indeed very good and professionally written. However, it doesn’t explain some basics which are very important for understanding PS features. It feels like you are being dragged into a dark and scary forest of this bloody PowerShell. On the serious note, I could say that this book was written by PS gurus who can barely walk in the shoes of ordinary Linux users or SW engineers.

Instead of it, I would recommend checking out this one:

Santos, Donabel. “PowerShell for SQL Server essentials.” (2015).

It has it all, plus puts it into SQL server context. Delicious!

I very much like the author’s style and the way of approaching main concepts. He just explains it to you as to a colleague without trying to impress you with his deep knowledge of the subject.

Great job, Mr. Santos!