Q: "Copy files from files
directory to templates
directory in a role."
Given the project for testing
shell> pwd
/scratch/tmp7/test-359
shell> tree .
.
├── ansible.cfg
├── hosts
├── pb.yml
├── roles
│ └── data
│ ├── defaults
│ ├── files
│ │ └── application.j2
│ ├── tasks
│ └── templates
├── roles2
│ └── roleX
└── roles3
└── roleY
A: I read this question as: "What is the directory of a role?"
If you're running a task in a role you can use the special variable role_path. But, this is not the case here. You want to copy the files inside the roles from a task in a playbook. Declare a dictionary with the roles and files you want to transfer between the directories files and templates
transfer_files:
data:
- application.j2
There might be more directories in DEFAULT_ROLES_PATH. For example,
shell> grep roles_path ansible.cfg
roles_path = $PWD/roles:$PWD/roles2:$PWD/roles3
Get the variable
my_roles_path: "{{ lookup('config', 'DEFAULT_ROLES_PATH') }}"
gives
my_roles_path:
- /scratch/tmp7/test-359/roles
- /scratch/tmp7/test-359/roles2
- /scratch/tmp7/test-359/roles3
Find all roles
- find:
paths: "{{ my_roles_path }}"
file_type: directory
depth: 1
register: my_roles_out
and declare the variables
my_roles: "{{ my_roles_out.files|map(attribute='path') }}"
my_roles_dict: "{{ dict(my_roles|map('basename')|
zip(my_roles|map('dirname'))) }}"
gives
my_roles:
- /scratch/tmp7/test-359/roles/data
- /scratch/tmp7/test-359/roles2/roleX
- /scratch/tmp7/test-359/roles3/roleY
my_roles_dict:
data: /scratch/tmp7/test-359/roles
roleX: /scratch/tmp7/test-359/roles2
roleY: /scratch/tmp7/test-359/roles3
Now, you can copy the file(s)
- copy:
src: "{{ role_path }}/files/{{ item.1 }}"
dest: "{{ role_path }}/templates/{{ item.1 }}"
loop: "{{ transfer_files|dict2items|subelements('value') }}"
vars:
role_path: "{{ my_roles_dict[item.0.key] }}/{{ item.0.key }}"
gives
shell> tree .
.
├── ansible.cfg
├── hosts
├── pb.yml
├── roles
│ └── data
│ ├── defaults
│ ├── files
│ │ └── application.j2
│ ├── tasks
│ └── templates
│ └── application.j2 <-- from files
├── roles2
│ └── roleX
└── roles3
└── roleY
Example of a complete playbook for testing
- hosts: localhost
vars:
my_roles_path: "{{ lookup('config', 'DEFAULT_ROLES_PATH') }}"
my_roles: "{{ my_roles_out.files|map(attribute='path') }}"
my_roles_dict: "{{ dict(my_roles|map('basename')|
zip(my_roles|map('dirname'))) }}"
transfer_files:
data:
- application.j2
tasks:
- debug:
var: my_roles_path
- find:
paths: "{{ my_roles_path }}"
file_type: directory
depth: 1
register: my_roles_out
- debug:
var: my_roles
- debug:
var: my_roles_dict
- copy:
src: "{{ role_path }}/files/{{ item.1 }}"
dest: "{{ role_path }}/templates/{{ item.1 }}"
loop: "{{ transfer_files|dict2items|subelements('value') }}"
vars:
role_path: "{{ my_roles_dict[item.0.key] }}/{{ item.0.key }}"