我正在嘗試將 json 檔案從本地主機復制到遠程主機,并使用 json“版本”鍵值作為目標檔案名中的引數。
JSON:
{"name": "test", "version": 3}
YML:
---
- name: Get json file version
hosts: locahost
become: true
tasks:
- name: Register licenses file
command: "cat conf/licenses.json"
register: result
- name: Save the json data
set_fact:
jsondata: "{{ result.stdout | from_json }}"
- name: Save licenses file version
set_fact:
file_version: "{{ jsondata | json_query(jmesquery) }}"
vars:
jmesquery: 'version'
- name: Deploy Licenses File
hosts: hosts
become: true
tasks:
- name: Copy licenses file
copy:
src: "conf/licenses.json"
dest: "/tmp/licenses_{{ file_version }}.json"
當我運行上面的劇本時,Deploy Licenses File 密鑰找不到 file_version 事實,即使我可以看到它已成功保存在 Get json file version 密鑰中。
設定 file_version 事實:
ok: [localhost] => {
"ansible_facts": {
"file_version": "1"
},
"changed": false
}
錯誤:
The task includes an option with an undefined variable. The error was: 'file_version' is undefined
我認為事實保存在給定的主機粒度上,而不是每個劇本啟動的全域事實。
我目前的解決方法是將密鑰組合到一個任務中,然后它可以正常作業,但我更喜歡獲得一次版本,而不是為每個遠程主機重復它。
uj5u.com熱心網友回復:
要訪問另一臺主機的事實,您始終可以使用hostvars 特殊變數。
所以,在你的情況下:
dest: "/tmp/licenses_{{ hostvars.localhost.file_version }}.json"
現在,您實際上不需要兩場比賽的那種復雜程度,并且可以做到:
- name: Deploy Licenses File
hosts: hosts
become: true
tasks:
- name: Copy licenses file
copy:
src: "{{ _licence_file }}"
dest: "/tmp/licenses_{{ file_version }}.json"
vars:
_licence_file: conf/licenses.json
file_version: >-
{{ (lookup('file', _licence_file) | from_json).version }}
uj5u.com熱心網友回復:
第一場比賽僅在本地主機上運行。因此,第一次播放中宣告的變數僅對localhost可用。這就是第二次播放中變數不可用的原因
錯誤是:“file_version”未定義
在所有主機上運行一次塊中的第一個任務。這樣,變數將在第二次播放中可供所有主機使用。例如,下面的簡化劇本可以完成這項作業
- hosts: all
tasks:
- block:
- include_vars:
file: licenses.json
name: jsondata
- set_fact:
file_version: "{{ jsondata.version }}"
run_once: true
- hosts: test_11
tasks:
- copy:
src: licenses.json
dest: "/tmp/licenses_{{ file_version }}.json"
在遠程主機上創建檔案
shell> ssh admin@test_11 cat /tmp/licenses_3.json
{"name": "test", "version": 3}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463816.html
