![Возможность переименовать файл только если он существует](https://rvso.com/image/760998/%D0%92%D0%BE%D0%B7%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%D1%81%D1%82%D1%8C%20%D0%BF%D0%B5%D1%80%D0%B5%D0%B8%D0%BC%D0%B5%D0%BD%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%84%D0%B0%D0%B9%D0%BB%20%D1%82%D0%BE%D0%BB%D1%8C%D0%BA%D0%BE%20%D0%B5%D1%81%D0%BB%D0%B8%20%D0%BE%D0%BD%20%D1%81%D1%83%D1%89%D0%B5%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82.png)
Мне нужно переименовать /jp/Test в /jp/test только если /jp/Test существует, в противном случае мне не нужно выполнять эту задачу. Если Both существует, мне нужно объединить оба в /jp/test
Я получаю следующую ошибку
{"msg": "The conditional check 'item.1.stat.exists == false and item.2.stat.exists == true' failed. The error was: error while evaluating conditional (item.1.stat.exists == false and item.2.stat.exists == true): dict object has no element 1\n\nThe error appears to be in
Пособие:
hosts: test
gather_facts: false
vars:
hostsfiles:
- /jp/test
- /jp/Test
tasks:
- name: Check if file exists
stat:
path: "{{ item}}"
with_items: "{{ hostsfiles }}"
register: jpresult
- name: test
shell: mv "{{item.2.stat.path}}" /jp/test
with_items:
- "{{ jpresult.results }}"
when: item.1.stat.exists == false and item.2.stat.exists == true
решение1
Ниже приведено рабочее решение. Обратите внимание, что вы можете задать владельца/разрешения для файла, созданного blockinfile
, и это blockinfile
добавит якоря вставки вокруг вставленного текста в файле назначения. Оба эти варианта можно настроить (см.документы)
- name: Some very cool play
hosts: test
gather_facts: false
vars:
destination_path: /jp/test
legacy_path: /jp/Test
tasks:
- name: Check if legacy file exists
stat:
path: "{{ legacy_path }}"
register: legacy_status
- name: Move contents of legacy file to destination file
when: legacy_status.stat.exists is true
block:
# Note that there is currently no module to read the contents of a
# file on the remote, so using "cat" via command is the best alternative
- name: Read contents of legacy file
command:
cmd: cat {{ legacy_path }}
register: legacy_contents
changed_when: false
- name: Add contents of legacy file to destination file
blockinfile:
path: "{{ destination_path }}"
state: present
block: "{{ legacy_contents.stdout }}"
# This ensures the file is created if it does not exist,
# saving an extra task to rename the file if necessary
create: true
- name: Remove legacy file
file:
path: "{{ legacy_path }}"
state: absent
Ошибка, которую вы там видите, возникает из-за того, что переменная цикла не является списком, а объектом словаря. Когда вы вызываете loop: "{{ jpresult.results }}"
(примечание, см.loop
противwith_
) значение {{ item }}
для каждой итерации цикла — это один элемент в списке, а не полный список. Чтобы получить доступ к значению статистики текущего индекса цикла, вы можете использовать item.stat
, или чтобы получить доступ к статистике другой итерации, вы можете использовать jpresult.results.N.stat
(где N
находится индекс, к которому вы хотите получить доступ).