Ich muss /jp/Test nur dann in /jp/test umbenennen, wenn /jp/Test vorhanden ist, andernfalls muss ich diese Aufgabe nicht ausführen. Wenn beide vorhanden sind, muss ich beide in /jp/test zusammenführen.
Ich erhalte den folgenden Fehler
{"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
Spielbuch:
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
Antwort1
Unten finden Sie eine funktionierende Lösung. Beachten Sie, dass Sie möglicherweise den Eigentümer/die Berechtigungen für die von erstellte Datei festlegen möchten blockinfile
. Dadurch blockinfile
werden Einfügeanker um den eingefügten Text in der Zieldatei hinzugefügt. Beide können konfiguriert werden (siehedie Dokumente)
- 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
Der Fehler, den Sie dort haben, liegt daran, dass die Schleifenvariable keine Liste, sondern ein Wörterbuchobjekt ist. Wenn Sie aufrufen loop: "{{ jpresult.results }}"
(Hinweis: sieheloop
Gegenwith_
) der Wert von {{ item }}
für jede Iteration der Schleife ist ein einzelnes Element in der Liste und nicht die vollständige Liste. Um auf den Statistikwert des aktuellen Schleifenindex zuzugreifen, können Sie verwenden item.stat
, oder um auf den Statistikwert einer anderen Iteration zuzugreifen, können Sie verwenden jpresult.results.N.stat
(wobei N
der Index ist, auf den Sie zugreifen möchten).