# Canonical way to correct a broken symlink

**URL:** <https://forum.ansible.com/t/canonical-way-to-correct-a-broken-symlink/23412>\
**Category:** Ansible Project\
**Created:** [January 9, 2017, 8:26pm UTC](https://forum.ansible.com/t/canonical-way-to-correct-a-broken-symlink/23412 "2017-01-09T20:26:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Lorens\_Kockum](https://avatars.discourse-cdn.com/v4/letter/l/f08c70/32.png) [@Lorens\_Kockum](https://forum.ansible.com/u/Lorens_Kockum)\
**Post date:** [January 9, 2017, 8:26pm UTC](https://forum.ansible.com/t/canonical-way-to-correct-a-broken-symlink/23412/1 "2017-01-09T20:26:30Z")

</div>

Hi,

I’m just starting out with Ansible, and I probably haven’t yet read all the docs I should, but I’m trying, so bear with me.

I have a simple play:

- name: test  
file:  
path: “/path/to/file”  
owner: username  
group: usergroup  
mode: 0644  
follow: yes

My problem is that while this is sometimes a file and sometimes a link to another file, it is also sometimes a broken symlink (literally to “None” in my case, how that happens is another problem), and my play stops short (in check mode!) saying that I need to specify “force” to create the destination.

I do not want to create the destination (especially since it’s “None”); if the symlink is broken I would like to replace it with an empty file (or maybe a template), unless I’m in check mode when I should simply note that a correction should be made.

Googling ansible and broken symlink didn’t help me, so I started out with the stat module, and conditionals on the values and success of stat, asking myself if stat.originalfile is the destination of the link, and if I should use that or do two stats on the file, one with follow and one without, and when I was on my fourth task I decided to ask you all whether there’s a simpler way 🙂

HAND

---

<div class="post-metadata">

**Author:** ![Johannes\_Kastl](https://avatars.discourse-cdn.com/v4/letter/j/bbe5ce/32.png) [@Johannes\_Kastl](https://forum.ansible.com/u/Johannes_Kastl)\
**Post date:** [January 10, 2017, 7:43am UTC](https://forum.ansible.com/t/canonical-way-to-correct-a-broken-symlink/23412/2 "2017-01-10T07:43:23Z")

</div>

Basically I guess you would have to check first, what state you have,  
e.g. a file, a link or a broken link. I guess using the stat module  
should do most of this.

[https://docs.ansible.com/stat\_module.html](https://docs.ansible.com/stat_module.html)

Register the variable of this task and depending on its result start  
your other tasks.

[https://docs.ansible.com/playbooks\_variables.html](https://docs.ansible.com/playbooks_variables.html)

I'm in a hurry, so please excuse my brevity.

Johannes
