Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible datetime timezone conversion

Is there a way to convert ansible date into a different timezone in a "debug" statement in my playbook ? I dont want a global timezone setting at the playbook level. I have this :

  debug:
   msg: "{{ '%Y-%m-%d %H:%M:%S' | strftime(ansible_date_time.epoch) }}"

This works fine but displays time in UTC. I need the time to be displayed in EDT without setting timezone at the global playbook level. How do I accomplish this ?

like image 603
user1722908 Avatar asked Oct 28 '25 14:10

user1722908


1 Answers

If you use a command task to run date rather than relying on the ansible_date_time variable, you can set the timezone via an environment variable. E.g. the following playbook:

- hosts: localhost
  vars:
    ansible_python_interpreter: /usr/bin/python
  tasks:
    - command: "date '+%Y-%m-%d %H:%M:%S'"
      register: date_utc
      environment:
        TZ: UTC

    - command: "date '+%Y-%m-%d %H:%M:%S'"
      register: date_us_eastern
      environment:
        TZ: US/Eastern

    - debug:
        msg:
          - "{{ date_utc.stdout }}"
          - "{{ date_us_eastern.stdout }}"

Results in this output:


PLAY [localhost] *****************************************************************************

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

TASK [command] *******************************************************************************
changed: [localhost]

TASK [command] *******************************************************************************
changed: [localhost]

TASK [debug] *********************************************************************************
ok: [localhost] => {
    "msg": [
        "2020-05-12 15:21:05",
        "2020-05-12 11:21:06"
    ]
}

PLAY RECAP ***********************************************************************************
localhost                  : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
like image 122
larsks Avatar answered Oct 30 '25 08:10

larsks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!