-1

Is there a way to copy a file meantime create folder if it does not exists?

Below is my code to copy, however, it does not work as it create source_code_management as a file, not as a directory.

- name: Transfer file
  copy:
    src: "{{ playbook_dir }}/roles/source_code_management/logger.xml"
    dest: "{{ configuration_path }}"

The reason I wish to create and copy at same time is that Jenkins, will pass path/file_name.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
james
  • 1
  • Does this answer your question? [What's the easy way to auto create non existing dir in ansible](https://stackoverflow.com/questions/22472168/whats-the-easy-way-to-auto-create-non-existing-dir-in-ansible) – β.εηοιτ.βε Jul 11 '20 at 17:56
  • thanks. this saw previously . this is template. mine would not be using template as sometimes will be xml, some files is jpg – james Jul 12 '20 at 01:13
  • You do have what we call an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) what you are trying to achieve is impossible in Ansible, but because you do not explain us here what you are trying to achieve, this is impossible to help you. This said, the explanation of what you are trying to achieve is now under the existing answer to your question, so I will edit it in your question. – β.εηοιτ.βε Jul 12 '20 at 09:02

2 Answers2

0

you need to add task before that to ensure that the directory exists:

- name: Directory source code exists
  file:
    src: "{{ playbook_dir }}/roles/source_code_management"
    state: directory

This is how it works till now ( ansible 2.9 and before )

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • thanks saw this. but i wish to create and copy at same time. as from jenkins, it will pass path/file_name – james Jul 12 '20 at 01:12
0

Sadly, you cannot do this in a single step with Ansible.

This said, if you have a /path/to/file stored in a variable, still there is an extra Jinja filter that would fit the job: the filter dirname that gets the directory from a path like /path/to/file.

With those you can, first create your directory, then copy you file:

- name: First, create the directory
  file:
    path: "{{ configuration_path | dirname }}"
    state: directory
    recurse: yes
- name: Then, transfer the file
  copy:
    src: "{{ playbook_dir }}/roles/source_code_management/logger.xml"
    dest: "{{ configuration_path }}"
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83