ansible ini_file 값 내에서 명령 출력을 사용하는 방법

ansible ini_file 값 내에서 명령 출력을 사용하는 방법

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_date_time사실을 수집하면 날짜와 시간을 유지합니다. 플레이북에서는 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. 대신 필터는strftime항상 현재 시간을 제공합니다. 예:

    - 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원격 서버에서 정보를 마지막으로 수집한 시간이 포함되며 반드시 현재 시간일 필요는 없습니다. 플레이북을 실행할 때마다 항상 사실을 수집한다면 이는 문제가 되지 않습니다.

관련 정보