![如何在 ansible ini_file 值中使用指令的輸出](https://rvso.com/image/768927/%E5%A6%82%E4%BD%95%E5%9C%A8%20ansible%20ini_file%20%E5%80%BC%E4%B8%AD%E4%BD%BF%E7%94%A8%E6%8C%87%E4%BB%A4%E7%9A%84%E8%BC%B8%E5%87%BA.png)
我想在 ini_file 中設定一個值,但該值是當前時間的 MD5 哈希值。 (我不怕意外替換該值,或者神奇地運行兩次並在兩個不同的伺服器中具有相同的值。)
這是我嘗試過的,但只得到了命令作為文件中的值(我不知道為什麼我認為它會起作用...):
- name: Replace HardwareID with new MD5
ini_file:
path: /etc/app/config.ini
section: DEFAULT
option: hardware_token
value: $(date | md5sum | cut -d" " -f1)
有沒有簡單的方法可以讓它發揮作用?
答案1
問:」如何使用 Ansible ini_file 值中指令的輸出?」
A:註冊命令的結果並將其用作值,例如
- hosts: test_24
gather_facts: false
tasks:
- shell: 'date | md5sum | cut -d" " -f1'
register: result
check_mode: false
- debug:
var: result
- name: Replace HardwareID with new MD5
ini_file:
path: etc/app/config.ini
section: DEFAULT
option: hardware_token
value: "{{ result.stdout }}"
給出(使用 --check --diff 運行)
TASK [Replace HardwareID with new MD5] ***********************************
--- before: etc/app/config.ini (content)
+++ after: etc/app/config.ini (content)
@@ -0,0 +1,3 @@
+
+[DEFAULT]
+hardware_token = ba3f11c4f1ecfe9d1e805dc8c8c8b149
changed: [test_24]
如果您想使用資料和時間作為輸入,那麼使用 Ansible 事實會更容易。例如,字典ansible_日期_時間如果您收集了事實,請保留日期和時間。在劇本中,我們設定了gather_facts: false
.因此字典沒有定義
- debug:
var: ansible_date_time.iso8601
給出
ok: [test_24] =>
ansible_date_time.iso8601: VARIABLE IS NOT DEFINED!
gather_facts: true
當你開始比賽或逃跑時,你必須收集事實setup
,例如
- setup:
gather_subset: min
- debug:
var: ansible_date_time.iso8601
給出
ok: [test_24] =>
ansible_date_time.iso8601: '2021-07-29T21:32:26Z'
這不是很實用,因為要取得當前時間,您必須運行setup
。相反,過濾器時間始終為您提供當前時間,例如
- debug:
msg: "{{ '%Y-%m-%d %H:%M:%S' | strftime }}"
- name: Replace HardwareID with new MD5
ini_file:
path: etc/app/config.ini
section: DEFAULT
option: hardware_token
value: "{{'%Y-%m-%d' | strftime | hash('md5') }}"
給出
TASK [debug] ***************************************************************
ok: [test_24] =>
msg: '2021-07-29'
TASK [Replace HardwareID with new MD5] *************************************
--- before: etc/app/config.ini (content)
+++ after: etc/app/config.ini (content)
@@ -0,0 +1,3 @@
+
+[DEFAULT]
+hardware_token = 5847924805aa614957022ed73d517e7e
附帶說明:如果日期時間(以秒為單位)是索引,則使用此雜湊可能會非常快速地進行搜尋。
答案2
Ansible 可以產生自己的日期和時間字串,並進行自己的 MD5 求和,而無需呼叫外部程式。考慮:
---
- hosts: localhost
connection: local
tasks:
- debug:
msg: "{{ ansible_date_time.iso8601 | hash('md5') }}"
請注意,ansible_date_time
包含您上次從遠端伺服器收集事實的時間,不一定是當前時間。如果您總是收集每次劇本運行的事實,那麼這應該不是問題。