본문 바로가기

리눅스

[draft] Ansible Playbook에서 현재 날짜 및 시간 얻기

Ansible Playbook에서 현재 날짜 및 시간 얻기(ansible-playbook)

1. ansible_date_time fact 사용

Ansible에서는 facts 수집(gather_facts) 시 자동으로 다양한 시스템 정보를 가져옵니다.

이 중 ansible_date_time fact를 이용하면 현재 날짜 및 시간을 사용할 수 있습니다.

 

Playbook 예제

vim current_date_time1.yml
---
- name: 사용자 정의 변수에 현재 날짜 및 시간 저장
  hosts: all
  gather_facts: true

  tasks:

    # ansible_date_time fact 확인
    - name: Debug ansible_date_time
      debug:
        var: ansible_date_time

    # 사용자 정의 변수 생성
    - name: 사용자 정의 변수에 현재 날짜 및 시간 저장
      set_fact:
        current_date_time: "{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}{{ ansible_date_time.minute }}{{ ansible_date_time.second }}"

    # 결과 출력
    - name: Debug 현재 날짜 및 시간
      debug:
        var: current_date_time

실행

ansible-playbook -i ./inventory tmp/current_date_time1.yml --limit localhost
더보기

---

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

PLAY [사용자 정의 변수에 현재 날짜 및 시간 저장] ***************************************************

TASK [Gathering Facts] *****************************************************************************
ok: [localhost]

TASK [Debug ansible_date_time] *********************************************************************
ok: [localhost] => {
    "ansible_date_time": {
        "date": "2024-01-03",
        "day": "03",
        "epoch": "1704266954",
        "epoch_int": "1704266954",
        "hour": "16",
        "iso8601": "2024-01-03T07:29:14Z",
        "iso8601_basic": "20240103T162914413085",
        "iso8601_basic_short": "20240103T162914",
        "iso8601_micro": "2024-01-03T07:29:14.413085Z",
        "minute": "29",
        "month": "01",
        "second": "14",
        "time": "16:29:14",
        "tz": "KST",
        "tz_dst": "KST",
        "tz_offset": "+0900",
        "weekday": "수요일",
        "weekday_number": "3",
        "weeknumber": "01",
        "year": "2024"
    }
}

TASK [사용자 정의 변수에 현재 날짜 및 시간 저장] ***************************************************
ok: [localhost]

TASK [Debug 현재 날짜 및 시간] *********************************************************************
ok: [localhost] => {
    "current_date_time": "2024-01-03_162914"
}

PLAY RECAP *****************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

---

"current_date_time": "2024-01-03_162914"

2. lookup('pipe') 를 이용한 방법

Ansible lookup plugin 을 사용하면 컨트롤 노드에서 명령을 실행할 수 있습니다.

lookup('pipe', 'command') 형식으로 Linux 명령어 결과를 변수로 가져올 수 있습니다.

 

Playbook 예제

vim current_date_time2.yml
---
- name: 사용자 정의 변수에 현재 날짜 및 시간 저장
  hosts: all
  gather_facts: false

  tasks:

    # date 명령 실행
    - name: 현재 날짜 및 시간 조회
      set_fact:
        current_date_time: "{{ lookup('pipe', 'date +%Y%m%d_%H%M%S') }}"

    # 결과 출력
    - name: Debug 현재 날짜 및 시간
      debug:
        var: current_date_time

실행

ansible-playbook -i ./inventory tmp/current_date_time2.yml --limit localhost
더보기

---

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

PLAY [사용자 정의 변수에 현재 날짜 및 시간 저장] ***************************************************

TASK [현재 날짜 및 시간 조회] **********************************************************************
ok: [localhost]

TASK [Debug 현재 날짜 및 시간] *********************************************************************
ok: [localhost] => {
    "current_date_time": "20240103_163008"
}

PLAY RECAP *****************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

---

"current_date_time": "20240103_163008"

3. shell 모듈을 이용한 방법

Ansible의 shell 모듈을 사용하여 대상 서버에서 date 명령을 실행할 수도 있습니다.

 

Playbook 예제

vim current_date_time3.yml
---
- name: Shell을 사용하여 현재 날짜 및 시간 가져오기
  hosts: all
  gather_facts: true

  tasks:

    - name: 현재 날짜 가져오기
      shell: date +%Y-%m-%dT%H:%M:%SZ
      register: current_date_time

    - name: Debug 현재 날짜 및 시간
      debug:
        var: current_date_time.stdout

실행

ansible-playbook -i ./inventory tmp/current_date_time3.yml --limit localhost
더보기

---

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

PLAY [Shell을 사용하여 현재 날짜 및 시간 가져오기] *************************************************

TASK [Gathering Facts] *****************************************************************************
ok: [localhost]

TASK [현재 날짜 가져오기] **************************************************************************
changed: [localhost]

TASK [Debug 현재 날짜 및 시간] *********************************************************************
ok: [localhost] => {
    "current_date_time": {
        "changed": true,
        "cmd": "date +%Y-%m-%dT%H:%M:%SZ",
        "delta": "0:00:00.043700",
        "end": "2024-01-03 16:30:39.739427",
        "failed": false,
        "msg": "",
        "rc": 0,
        "start": "2024-01-03 16:30:39.695727",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "2024-01-03T16:30:39Z",
        "stdout_lines": [
            "2024-01-03T16:30:39Z"
        ]
    }
}

PLAY RECAP *****************************************************************************************
localhost                  : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

---

current_date_time.stdout: "2024-01-03T16:30:39Z"

자주 사용하는 예시

로그 파일 이름 생성

log_file: "backup_{{ lookup('pipe', 'date +%Y%m%d_%H%M%S') }}.log"
backup_20240103_163008.log

백업 디렉토리 생성

backup_dir: "/backup/{{ ansible_date_time.date }}"
/backup/2024-01-03

 

참고URL

- Ansible Documentation : ansible_date_time facts

- Ansible Documentation : lookup commands

- Ansible Documentation : shell commands