Search code examples
amazon-web-servicesamazon-ec2aws-clijmespath

AWS CLI How to check if images follows a special pattern tag value


I'm trying to filter the images that follow the following pattern in their tag value: dev/yyyy-mm-dd eg. : dev/2021-09-11

the best idea that came up to me was something like this:

aws ec2 describe-images --filters Name=tag:tag_name,Values="dev/????-??-??"

is there a more logical approach?


Solution

  • You would use the boto3 AWS SDK to call AWS directly, something like:

    import boto3
    from datetime import datetime
    
    FIND_TAG = 'your-tag'
    
    ec2_resource = boto3.resource('ec2')
    
    images = ec2_resource.images.filter(Owners=['self'])
    
    # Find the matching tag
    for image in images:
      values = [tag['Value'] for tag in image.tags if tag['Key'] == FIND_TAG]
    
    if len(values) > 0:
      value = values[0]
    
      # Is it a date?
      try:
        date = datetime.strptime(value, '%Y-%m-%d')
      except ValueError:
        print('Not a date')