![只有當檔案存在時才可以重新命名](https://rvso.com/image/760998/%E5%8F%AA%E6%9C%89%E7%95%B6%E6%AA%94%E6%A1%88%E5%AD%98%E5%9C%A8%E6%99%82%E6%89%8D%E5%8F%AF%E4%BB%A5%E9%87%8D%E6%96%B0%E5%91%BD%E5%90%8D.png)
只有當 /jp/Test 存在時,我才需要將 /jp/Test 重新命名為 /jp/test ,否則我不需要執行此任務。如果兩者都存在,我需要將兩者合併到 /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 }}
) for 迴圈每次迭代的值是清單中的單一項目,而不是完整列表。若要存取目前循環索引的統計值,您可以使用item.stat
,或存取不同迭代的統計值,您可以使用jpresult.results.N.stat
(其中N
是您要存取的索引)。