Skip to content

Instantly share code, notes, and snippets.

@straight-shoota
Created February 29, 2016 23:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save straight-shoota/7a41493ff76aa5d1ef6f to your computer and use it in GitHub Desktop.
Save straight-shoota/7a41493ff76aa5d1ef6f to your computer and use it in GitHub Desktop.
Unlink unused config files in sites-enabled with Ansible

This task cleans sites-enabled dir from config files that should not be enabled anymore Its quite easy to use a list of enabled sites to link their config files to sites-enabled, as shown in the last entry. There will still be links to the config files of sites that had been enabled in the previous ansible run, they need to be removed explicitly. The simple way would be to remove the sites-enablied directory alltogether. But this would allways require to create new links to the config files for enabled sites. Thus it would force a server restart even if there had really no changes at all. Defining a var disabled_sites is not quite a good idea since you would probably forget to add or remove items from that list at one time. So my solution is to list all config files that do not correspond to enabled sites and in a second step remove those.

I use it with nginx, but it should also work with apache/httpd or other configurations with a similar concept.

It would be easier to use just rm with an extended glob like rm /etc/nginx/sites-enabled/!({{ enabled_sites | join('|') }}).conf. Unfortunately this is no so easy with ansible since extglob is not available by default in the shell module. It's possible to explicitly use an specific executable bin like /bin/bash. /bin/bash -O extglob should do the trick but I couldn't get it to run with an argument. You cant just prepend setopt -s extglob in the same shell command because the extglob will result in an parse error since it is not enabled at parse time. The only way to use extendend globs would be to put a script on the remote host - either to run a shell with extglob or to execute the command by /bin/bash -O extglob script. Anyway, ls with --ignore seems quite easier.

- name: NGINX | Find disabled sites
shell: "ls {% for site in enabled_sites %} --ignore={{ site }}.conf{% endfor %}"
args:
chdir: /etc/nginx/sites-enabled
register: disabled_sites
changed_when: false
tags: [remove-sites]
- name: NGINX | Remove disabled sites
file: dest=/etc/nginx/sites-enabled/{{ item }} state=absent
notify: restart nginx
tags: [remove-sites]
with_items: "{{ disabled_sites.stdout_lines }}"
# just to complete the setup
- name: NGINX | Enable sites
file: dest=/etc/nginx/sites-enabled/{{ item }}.conf src=/etc/nginx/sites-available/{{ item }}.conf state=link
with_items: "{{ enabled_sites }}"
notify: restart nginx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment