![存在する場合にのみファイルの名前を変更する Ansible](https://rvso.com/image/760998/%E5%AD%98%E5%9C%A8%E3%81%99%E3%82%8B%E5%A0%B4%E5%90%88%E3%81%AB%E3%81%AE%E3%81%BF%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E5%90%8D%E5%89%8D%E3%82%92%E5%A4%89%E6%9B%B4%E3%81%99%E3%82%8B%20Ansible.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 }}
、完全なリストではなく、リスト内の単一の項目です。現在のループ インデックスの統計値にアクセスするには を使用し、別の反復の統計値にアクセスするには(はアクセスするインデックスです)item.stat
を使用します。jpresult.results.N.stat
N