Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding file name in files section of current Ansible role

I'm fairly new to Ansible and I'm trying to create a role that copies a file to a remote server. The local file can have a different name every time I'm running the playbook, but it needs to be copied to the same name remotely, something like this:

- name: copy file
  copy:
    src=*.txt
    dest=/path/to/fixedname.txt

Ansible doesn't allow wildcards, so when I wrote a simple playbook with the tasks in the main playbook I could do:

- name: find the filename
    connection: local
    shell: "ls -1 files/*.txt"
    register: myfile

- name: copy file
  copy:
    src="files/{{ item }}"
    dest=/path/to/fixedname.txt
  with_items:
   - myfile.stdout_lines

However, when I moved the tasks to a role, the first action didn't work anymore, because the relative path is relative to the role while the playbook executes in the root dir of the 'roles' directory. I could add the path to the role's files dir, but is there a more elegant way?

like image 219
hepabolu Avatar asked Jun 16 '14 19:06

hepabolu


People also ask

What is the name of the file that configures the Ansible role?

ansible. cfg (in the home directory) /etc/ansible/ansible. cfg.

Where are Ansible files located?

You can control the paths Ansible searches to find resources on your control node (including configuration, modules, roles, ssh keys, and more) as well as resources on the remote nodes you are managing.

Where are role dependencies stored in Ansible?

If roles/x/meta/main. yml exists, Ansible adds any role dependencies in that file to the list of roles. Any copy, script, template or include tasks (in the role) can reference files in roles/x/{files,templates,tasks}/ (dir depends on task) without having to path them relatively or absolutely.

What is recurse in Ansible?

recurse. boolean. added in 1.1 of ansible.builtin. Recursively set the specified file attributes on directory contents. This applies only when state is set to directory .


1 Answers

Just wanted to throw in an additional answer... I have the same problem as you, where I build an ansible bundle on the fly and copy artifacts (rpms) into a role's files folder, and my rpms have versions in the filename.

When I run the ansible play, I want it to install all rpms, regardless of filenames.

I solved this by using the with_fileglob mechanism in ansible:

- name: Copy RPMs
  copy: src="{{ item }}" dest="{{ rpm_cache }}"
  with_fileglob: "*.rpm"
  register: rpm_files

- name: Install RPMs
  yum: name={{ item }} state=present
  with_items: "{{ rpm_files.results | map(attribute='dest') | list }}"

I find it a little bit cleaner than the lookup mechanism.

like image 113
zedix Avatar answered Oct 12 '22 13:10

zedix