Ansible date compare EC2

2019-02-19 15:11发布

I am new to Ansible . I created EC2 instances using ansible and able to to retrieve the launch time using EC2 facts .

But i am unable to store the launch time in date format .

My goal is to get the difference of launch time date with system date (unable to find that also and perform some operations .

Any guidance is appreciated .

Regards, Naresh Sharma

标签: ansible
1条回答
可以哭但决不认输i
2楼-- · 2019-02-19 15:31

Since Ansible 2.2 there is a handy to_datetime(format) filter available.

Here is example for your task:

---
- hosts: localhost
  gather_facts: yes
  tasks:
    - name: local date
      debug:
        msg: "{{ ansible_date_time.iso8601 }}"
    - ec2_remote_facts:
        region: eu-west-1
      register: ec2
    - name: instance date
      debug:
        msg: "{{ ec2.instances[0].launch_time }}"
    - name: date difference in days
      debug:
        msg: "{{ (ansible_date_time.iso8601[:19] | to_datetime(fmt) - ec2.instances[0].launch_time[:19] | to_datetime(fmt)).days }}"
      vars:
        fmt: "%Y-%m-%dT%H:%M:%S"

Note [:19] to get first 19 characters to avoid handling of milliseconds and timezone characters.

Result:

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

TASK [setup] *******************************************************************
ok: [localhost]

TASK [local date] **************************************************************
ok: [localhost] => {
    "msg": "2017-02-03T18:39:12Z"
}

TASK [ec2_remote_facts] ********************************************************
ok: [localhost]

TASK [instance date] ***********************************************************
ok: [localhost] => {
    "msg": "2016-09-21T15:43:40.000Z"
}

TASK [date difference in days] *************************************************
ok: [localhost] => {
    "msg": "135"
}

PLAY RECAP *********************************************************************
localhost                  : ok=5    changed=0    unreachable=0    failed=0
查看更多
登录 后发表回答