2

I want to achieve the following - in a directory 'sites-enabled' to have only the symlinks present that are defined in a list {{ sites_enabled }}

Specifically the difficulty is with - how can I make Ansible have only the defined in the list links present, and what is not in the list - removed.

I have come up with following solution, that is sub-optimal:

# 3. Disable all links (clean plate)
- name: Disable all enabled vhosts.
  file: path="{{ remote_enabled_cfg_dir }}/{{ item }}" state=absent
  with_fileglob:
    - "{{ remote_enabled_cfg_dir }}/*"

# 4. Enable only the approved vhosts / Create Link from sites-available to sites-enabled
- name: Enable only allowed vhosts
  file:
    src: "{{ remote_cfg_dir }}/{{ item }}"
    dest: "{{ remote_enabled_cfg_dir }}/{{ item }}"
    owner: root
    group: wheel
    state: link
  with_items: "{{ sites_enabled }}"
  notify: reload nginx

however, I don't fancy removing all valid symlinks only to recreate them a moment later and have to reload nginx on every play. (I would prefer if there was no change since last play, no action to be taken by Ansible) Is there a more clever way to achieve this goal?

  • 1
    You should be able to read all the symlinks in an array, then loop over them and match (possible as in stackoverflow.com/questions/29161274/… ) - my Ansible knowledge is not sufficient to give full answer, though. – Richlv May 31 '18 at 18:59
0

I use the difference Jinja filter for this purpose. Add a task to list the contents of your config dir and register the result in a variable. Then add a task that removes invalid items from the config directory by finding the difference between your list of valid files and those found in the previous step:

- name: Get contents of config directory
  command: ls "{{ remote_cfg_dir }}"
  register: cfg_dir_contents
- name: Remove invalid files from config directory
  file:
    dest: "{{ remote_cfg_dir }}/{{ item }}"
    state: absent
  loop: "{{ cfg_dir_contents.stdout_lines | difference(sites_enabled) }}"

(Assumes that 'sites_enabled' is simply a list of names of files that should exist in 'remote_cfg_dir')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.