Ansible: Using register with with_items


The motivation for this came from trying implement running a command that depended on whether or not a previous command succeeded.

In this case, I was trying to make the creation of duply profiles idempotent. Duply will exit with an error if you attempt to create a profile that already exists, and I didn’t want that to interrupt my playbook.

My first thought was “stat the folder & check if it exists”, which got my this:
[generic]
– name: Check if profile exists
stat: >
path={{duply_path}}/{{item.key}}/
with_dict: “{{folders}}”
register: profile
– name: Create duply profiles
command: duply {{item.0}} create
with_together:
– “{{folders}}”
– profile.results
when: item.1.stat.isdir is not defined
[/generic]
I semi-abused the with_together operator to link both my dict of folders & the results of the stat on each of the folders.

Turns out each element in the result from the stat call also contains a copy of the item it was called with, which meant my code could be reduced to
[generic]
– name: Check if profile exists
stat: >
path={{duply_path}}/{{item.key}}/
with_dict: “{{folders}}”
register: profile
– name: Create duply profiles
command: duply {{item.item.key}} create
with_items: profile.results
when: item.stat.isdir is not defined
[/generic]
The key difference is that I used {{item.item}} to get access to the original item that was passed to the stat task.

Of course, it turns out that I don’t need the extra stat call, since I can just use the creates parameter to the command task, making my code even shorter:
[generic]
– name: Create duply profiles
command: duply {{item.key}} create creates={{duply_path}}/{{item.key}}
with_dict: “{{folders}}”
[/generic]
I ended up dropping the whole register bit, but I wanted to note this down for the future, because it’s fairly interesting behaviour.

  1. No comments yet.
(will not be published)