EC2 comparing dates

105 views
Skip to first unread message

Tony

unread,
Sep 11, 2021, 12:09:48 PM9/11/21
to Ansible Project
Hi, would really appreciate some help if possible.

I am using ec2_ami_info to capture the creation date.

I register the output as ami_creation_date.

Output is: 2021-09-09

I would like to delete the AMI if it is 2 days older than now.

I've tried some code I've used in the past but getting templating errors etc.

Using the latest release of AWX.

Would really appreciate it if someone can help :)

thank you!

david...@mycit.ie

unread,
Sep 11, 2021, 2:56:24 PM9/11/21
to Ansible Project

Tony

unread,
Sep 12, 2021, 3:50:48 AM9/12/21
to Ansible Project
Thanks David

I have tried similar to the above but get a templating error:

{
  "msg": "Unexpected templating type error occurred on ({{ ( (ansible_date_time.date - date_earlier).total_seconds() / 3600 ) | int }}): unsupported operand type(s) for -: 'AnsibleUnsafeText' and 'dict'",
  "_ansible_no_log": false
}

Here is my code:

---
- hosts: localhost
  gather_facts: true
  tasks:
  

  - name: Get AMI info
    amazon.aws.ec2_ami_info:
      aws_access_key: "{{ lookup('env','AWS_ACCESS_KEY_ID') }}"
      aws_secret_key: "{{ lookup('env','AWS_SECRET_ACCESS_KEY') }}"
      region: eu-west-1
      filters:
        "tag:Backup_Policy": 1
    register: date_earlier

  - name: Compare AMI date
    debug:
      msg: "{{ ( (ansible_date_time.date - date_earlier).total_seconds() / 3600 ) | int }}"

Any help would be appreciated

Tony

unread,
Sep 12, 2021, 4:18:35 AM9/12/21
to Ansible Project
Sorry, that was out of date code, see below for latest

---
- hosts: localhost
  gather_facts: true
  tasks:
  
  - name: Date
    debug:
      msg: "{{ ansible_date_time.date }}"
    register: date_later

  - name: Get AMI info
    amazon.aws.ec2_ami_info:
      aws_access_key: "{{ lookup('env','AWS_ACCESS_KEY_ID') }}"
      aws_secret_key: "{{ lookup('env','AWS_SECRET_ACCESS_KEY') }}"
      region: eu-west-1
      filters:
        "tag:Backup_Policy": 1
    register: ec2_ami_info

  - name: AMI Date
    debug:
       msg: "{{ ec2_ami_info.images.0.creation_date[:10] }}"
    register: date_earlier

  - name: test
    debug:
      msg: "{{ ( (date_later - date_earlier).total_seconds() / 3600 ) | int }}"



Tony

unread,
Sep 12, 2021, 4:20:02 AM9/12/21
to Ansible Project
{
  "msg": "Unexpected templating type error occurred on ({{ ( (date_later - date_earlier).total_seconds() / 3600 ) | int }}): unsupported operand type(s) for -: 'dict' and 'dict'",
  "_ansible_no_log": false

Tony

unread,
Sep 12, 2021, 11:25:09 AM9/12/21
to Ansible Project
Anyone help me on this one please :)

I think I need to convert string to date but I cannot seem to get it to work.

Cheers!

david...@mycit.ie

unread,
Sep 12, 2021, 3:30:53 PM9/12/21
to Ansible Project
Really not sure why you are trying to use Ansible for this type of workflow  ?

Using Boto3 would be much better

.
import boto3
import datetime


LaunchAge = 30

def days_old(date):
    date_obj = date.replace(tzinfo=None)
    diff = datetime.datetime.now() - date_obj
    return diff.days

ec2 = boto3.client('ec2')
instance = ec2.describe_instances()
for i in instance['Reservations']:
    for instance in i["Instances"]:
        instance_id = instance["InstanceId"]
        LaunchDate = instance['LaunchTime']

        day_old = days_old(LaunchDate) # Get Date from Launch

        if day_old > LaunchAge:
          response = ec2.stop_instances(InstanceIds=[instance_id])
          print(response)


Tony

unread,
Sep 12, 2021, 5:38:27 PM9/12/21
to Ansible Project
Hi, bit of an odd statement no?

I use Ansible with AWX to make use of the task scheduling amongst all the other features. 

This is just another use case to add to the list of many.

I think you may have misunderstood what I am trying to achieve.

This usecase is for a backup schedule.

I want to remove any AWS AMIs 2 days older than current date.

Oskar Almlöv

unread,
Sep 13, 2021, 6:00:29 AM9/13/21
to ansible...@googlegroups.com

Hi,

When you register the debug task you are not only handed back the printed string but a dictionary containing information about the task execution.
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#registering-variables

What goes wrong is that in your code you are trying to subtract a dictionary (date_earlier) from a string.

Take a look at the below example and I think things will become clearer:


user@dev:~/code/snippets$ cat register.yml
#!/usr/bin/ansible-playbook
---
- hosts: localhost
  gather_facts: false
  vars:
    test: thisisastring
  tasks:
    - debug:
        msg: "{{ test[:10] }}"
      register: registered_var

    - debug:
        var: registered_var

user@dev:~/code/snippets$ ./register.yml
PLAY [localhost] ******************************************************************************

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "msg": "thisisastr"
}

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "registered_var": {
        "changed": false,
        "failed": false,
        "msg": "thisisastr"
    }
}

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


If you to create a new variable you should instead use the ansible.builtin.set_fact module.
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html

//Oskar

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/e4de2516-c9a2-4e30-a85a-bc9498bec14fn%40googlegroups.com.

Tony

unread,
Sep 13, 2021, 6:34:14 AM9/13/21
to Ansible Project
Hi Oskar,

That makes sense, thank you

I now get a different error.

Here is the code:

---
- hosts: localhost
  gather_facts: true
  vars:
    date_1: 2021-09-10T19:02:06.000Z
  tasks:
  
  - name: Date
    set_fact:
      date_later: "{{ ansible_date_time.iso8601 }}"
    
  - name: Get AMI info
    amazon.aws.ec2_ami_info:
      aws_access_key: "{{ lookup('env','AWS_ACCESS_KEY_ID') }}"
      aws_secret_key: "{{ lookup('env','AWS_SECRET_ACCESS_KEY') }}"
      region: eu-west-1
      filters:
        "tag:Backup_Policy": 1
    register: ec2_ami_info

  - name: AMI Date
    set_fact:
       date_earlier: "{{ ec2_ami_info.images.0.creation_date }}"
  
  - debug:
       var: date_earlier
  
  - debug:
       var: date_later
       
  - name: date difference
    debug:
      msg: "{{ ( (date_earlier - date_earlier).total_seconds() / 86400) | int }}"


Here is the error:

{
  "msg": "Unexpected templating type error occurred on ({{ ( (date_earlier - date_earlier).total_seconds() / 3600 ) | int }}): unsupported operand type(s) for -: 'AnsibleUnsafeText' and 'AnsibleUnsafeText'",
  "_ansible_no_log": false
}

thank you!

Oskar Almlöv

unread,
Sep 13, 2021, 6:46:01 AM9/13/21
to ansible...@googlegroups.com

HI,

When you set your fact it is being casted into a string and then you are trying to subtract a string from a string, which isn't possible.

You need to convert the variable to an integer in order to perform mathematical operations on it:

  - name: AMI Date
    set_fact:
       date_earlier: "{{ ec2_ami_info.images.0.creation_date | int }}"

Tony

unread,
Sep 13, 2021, 7:08:12 AM9/13/21
to Ansible Project
again, makes sense, thank you.

I've changed as you suggested but get the same error.

Thanks!

Tony

unread,
Sep 13, 2021, 8:48:06 AM9/13/21
to Ansible Project
thanks everyone for your help

Resolved with the below:

---
- hosts: localhost
  gather_facts: true
  vars:
  tasks:
  
  - name: Set current date
    set_fact:
      date_now: "{{ ansible_date_time.date }}"
    
  - name: Get AMI info
    amazon.aws.ec2_ami_info:
      aws_access_key: "{{ lookup('env','AWS_ACCESS_KEY_ID') }}"
      aws_secret_key: "{{ lookup('env','AWS_SECRET_ACCESS_KEY') }}"
      region: eu-west-1
      filters:
        "tag:Backup_Policy": 1
    register: ec2_ami_info

  - name: AMI Dates
    set_fact:
       ami_date: "{{ ec2_ami_info.images.0.creation_date[:10] }}"
       
  - name: Compare dates
    debug:
      msg: "{{ ( (date_now|to_datetime('%Y-%m-%d')) - (ami_date| to_datetime('%Y-%m-%d')) ).days  }}"
    register: ami_age

Reply all
Reply to author
Forward
0 new messages