I want to create the folder: temp2 which is able to store all the symlinks of the subfolders/files of other foder: temp1. with_items
can help complete this task, but it needs to list down all the folder/file name as below script shown:
- name: "create folder: temp2 to store symlinks"
file:
path: "/etc/temp2"
state: directory
- name: "create symlinks & store in temp2"
file:
src: "/etc/temp1/{{ item.src }}"
dest: "/etc/temp2/{{ item.dest }}"
state: link
force: yes
with_items:
- { src: 'BEAM', dest: 'BEAM' }
- { src: 'cfg', dest: 'cfg' }
- { src: 'Core', dest: 'Core' }
- { src: 'Data', dest: 'Data' }
It is not flexible as the subfolders/files under temp1 would be added or removed, and I need to update above script frequently to keep the symlinks as updated
Is there any way to detect all the files/folder under temp1 automatically instead of maintaining the with_items
list?
The following code works under Ansible-2.8:
- name: Find all files in ~/commands
find:
paths: ~/commands
register: find
- name: Create symlinks to /usr/local/bin
become: True
file:
src: "{{ item.path }}"
path: "/usr/local/bin/{{ item.path | basename }}"
state: link
with_items: "{{ find.files }}"
You can create a list of files using find
module:
Return a list of files based on specific criteria. Multiple criteria are AND’d together.
You'll likely need to leave recurse
set to false
(default) since you assume subfolders might exist.
You need to register the results of the module with register
declaration:
register: find
In the next step you need to iterate over the files
list from the results:
with_items: "{{ find.results.files }}"
and refer to the value of the path
key. You already know how to do it.
You will also need to extract the filename from the path, so that you can append it to the destination path. Use basename
filter for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With