Execute command only_if some file does not exists yet

Dear list,

I’m creating a playbook. In it I create a user. For that user I want to create an SSH key. But I want this to be idempotent. Currently I try to do this with:

  • name: generate an SSH key for ops
    action: command su -c ‘ssh-keygen -N “” -t rsa -f /home/ops/.ssh/id_rsa’ ops
    only_if: ‘not os.path.isfile(“/home/ops/.ssh/id_rsa”)’

The action clause seems to be evaluated before the only_if clause causing Ansible to hang as the command requires user input (“are you sure you want to overwrite?”).
I was thinking maybe I need to assign a variable in a vars block but I’m pretty sure I can’t do dynamic assignments there. Or maybe I’m going about this the wrong way entirely. I’d appreciate the help!

With kind regards,

Hi,

Dear list,

I'm creating a playbook. In it I create a user. For that user I want to
create an SSH key. But I want this to be idempotent. Currently I try to do
this with:
- name: generate an SSH key for ops
action: command su -c 'ssh-keygen -N "" -t rsa -f /home/ops/.ssh/id_rsa'
ops
only_if: 'not os.path.isfile("/home/ops/.ssh/id_rsa")'

Look at http://ansible.github.com/modules.html#command
There's a 'creates' parameter to the command/shell modules that does
what you want.

Greetings,

Jeroen

_< Can’t believe I missed that. Thanks a lot.

There were some patches to only_if that I applied around 10 EST last night that correct the order, however only_if works on facts only and that is evaluated "overlord" not "minion" side.

Since you are using command, the "creates" option to the module looks to be exactly what you want.

-- Michael

Beat me to it :slight_smile:

-- Michael