ansibleansible-2.x

How to pass today's date and time as argument in ansible


I am running python script using ansible.

Here is my playbook -

- name: Run python script 
  command: python Test.py -StartDate 2020-10-01T00:00:00 -EndDate 2020-11-05T00:00:00
  register: result
- debug: msg="{{result.stdout}}"

I want this playbook to use EndDate as todays date when I run script. How can I use latest date and time in same format I have written every time I run script without having to change manually every day?


Solution

  • assuming the T00:00:00 is always fixed, you could declare a variable using the lookup plugin, see an example below the exec_date variable and the modified command task:

    ---
    - hosts: localhost
      gather_facts: false
      vars:
        exec_date: "{{ lookup('pipe', 'date +%Y-%m-%d') }}T00:00:00"
    
      tasks:
      - name: print
        debug: var=exec_date
    
      - name: Run python script 
        command: "python Test.py -StartDate 2020-10-01T00:00:00 -EndDate {{ exec_date }}"
        register: result
      - debug: msg="{{result.stdout}}"
    

    If you want to pass the current time too instead of a fixed T00:00:00, you could use the below:

      vars:
        exec_date: "{{ lookup('pipe', 'date +%Y-%m-%dT%H:%M:%S') }}"
    

    cheers