Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a directory with a symlink using ansible?

Tags:

I would like to replace /etc/nginx/sites-enabled with a symlink to my repo. I'm trying to do this using file module, but that doesn't work as the file module doesn't remove a directory with force option.

- name: setup nginx sites-available symlink   file: path=/etc/nginx/sites-available src=/repo/etc/nginx/sites-available state=link force=yes   notify: restart nginx 

I could fall back to using shell.

- name: setup nginx sites-available symlink   shell: test -d /etc/nginx/sites-available && rm -r /etc/nginx/sites-available && ln -sT /repo/etc/nginx/sites-available /etc/nginx/sites-available   notify: restart nginx   

Is there any better way to achieve this instead of falling back to shell?

like image 282
Anand Chitipothu Avatar asked Nov 19 '14 00:11

Anand Chitipothu


People also ask

What is symlink in ansible?

Ansible create a symbolic link file , which means that is part of the collection of modules “builtin” with ansible and shipped with it. It's a module pretty stable and out for years. It works in a different variety of operating systems. It manages files and file properties.

What is recurse in ansible?

recurse. boolean. added in 1.1 of ansible.builtin. Recursively set the specified file attributes on directory contents. This applies only when state is set to directory .

Which module will you utilize to create a directory?

You can use the file module. To create a directory, you need to specify the option state=directory.


1 Answers

When you take your action, it's actually things:

  • delete a folder
  • add a symlink in its place

This is probably also the cleanest way to represent in Ansible:

tasks:   - name: remove the folder     file: path=/etc/nginx/sites-available state=absent     - name: setup nginx sites-available symlink     file: path=/etc/nginx/sites-available            src=/repo/etc/nginx/sites-available            state=link            force=yes     notify: restart nginx 

But, always removing and adding the symlink is not so nice, so adding a task to check the link target might be a nice addition:

  - name: check the current symlink     stat: path=/etc/nginx/sites-available      register: sites_available 

And a 'when' condition to the delete task:

  - name: remove the folder (only if it is a folder)     file: path=/etc/nginx/sites-available state=absent     when: sites_available.stat.isdir is defined and sites_available.stat.isdir 
like image 156
Ramon de la Fuente Avatar answered Oct 23 '22 16:10

Ramon de la Fuente