How to override role's file on Ansible?

6.1k Views Asked by At

I am using the zzet.rbenv role on my playbook. It has a files/default-gems file that it copies to the provisioned system.

I need my playbook to check for a myplaybook/files/default-gems and use it if it exists, using the zzet.rbenv/files/default-gems if otherwise.

How can I do that?

1

There are 1 best solutions below

2
On BEST ANSWER

After some research and trial/error. I found out that Ansible is not capable of checking if files exist between roles. This is due to the way role dependencies (which roles themselves) will get expanded into the one requiring it, making it part of the playbook. There are no tasks that will let you differentiate my_role/files/my_file.txt from required_role/files/my_file.txt.

One approach to the problem (the one I found the easiest and cleanest) was to:

  1. Add a variable to the my_role with the path to the file I want to use (overriding the default one)
  2. Add a task (identical to the one that uses the default file) that checks if the above variable is defined and run the task using it

Example

required_role

# Existing task
- name: some task
  copy: src=roles_file.txt dest=some/directory/file.txt
  when: my_file_path is not defined

# My custom task
- name: my custom task (an alteration of the above task)
  copy: src={{ my_file_path }} dest=/some/directory/file.txt
  when: my_file_path is defined

my_role

#... existing code 
my_file_path: "path/to/my/file"

As mentioned by Ramon de la Fuente: this solution was accepted into the zzet.rbenv repo :)