最簡單的方式,使用 vars 紀錄:
- hosts: YourTargetServers
vars:
rpm_dir: "/data/rpm/production/"
rpm_name_prefix: "packagename*"
rpm_find_command: "find {{ rpm_dir }} -name '{{ rpm_name_prefix }}' -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d ' ' "
rpm_path: "{{ lookup('pipe', 'rpm_find_command') }}"
tasks:
- name: find rpm prefix name
debug: msg="{{rpm_name_prefix}}"
- name: find rpm command
debug: msg="{{rpm_find_command}}"
- name: find rpm path
debug: msg="{{rpm_path}}"
這樣算是收工了,但是 rpm_path 若沒找到時,卻無法有洽當的錯誤偵測 Orz
所以第一次再改成這招:
- hosts: YourTargetServers
vars:
rpm_dir: "/data/rpm/production/"
rpm_name_prefix: "packagename*"
rpm_find_command: "find {{ rpm_dir }} -name '{{ rpm_name_prefix }}' -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d ' ' "
tasks:
- name: find rpm prefix name
debug: msg="{{rpm_name_prefix}}"
- name: find rpm command
debug: msg="{{rpm_find_command}}"
- name: find rpm path
local_action: command /bin/bash -c "{{ rpm_find_command }}"
sudo: False
failed_when: " '' != rpm_path_result.stderr"
- name: get rpm path
debug: msg="{{ rpm_path_result.stdout }}"
但這樣仍有個缺點,那就是若有 roles 等一堆工作,會變成那堆工作做完才會跑 tasks,這時就會希望先偵測本地端的資料在跑 roles 工作,於是乎又改成:
- hosts: loclahost
vars:
rpm_dir: "/data/rpm/production/"
rpm_name_prefix: "packagename*"
rpm_find_command: "find {{ rpm_dir }} -name '{{ rpm_name_prefix }}' -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d ' ' "
tasks:
- name: find rpm prefix name
debug: msg="{{rpm_name_prefix}}"
- name: find rpm command
debug: msg="{{rpm_find_command}}"
- name: find rpm path
local_action: command /bin/bash -c "{{ rpm_find_command }}"
failed_when: " '' != rpm_path_result.stderr"
- name: get rpm path
debug: msg="{{ rpm_path_result.stdout }}"
- hosts: YourTargetServers
vars:
rpm_path: "{{ hostvars['localhost']['rpm_path_result']['stdout'] }}"
tasks:
- name: find rpm path
debug: msg="{{rpm_path}}"
如此一來,就可以先確保在 localhost 把資源準備齊了,再進行遠端部署動作,也包含偵錯處理啦。
沒有留言:
張貼留言