Lambda Script to Query Trust Advisor and Find Idle Resources

Home   »   Lambda Script to Query Trust Advisor and Find Idle Resources

---
AWSTemplateFormatVersion: "2010-09-09"
Description:
   Create Event rule and lambda functions to report for following criteria 
   Idle EC2 instances if CPU < 10% and Network < 5MB
   RDS Instance with no connections for 7 days
   ELB with No Active backends and requests below 100
Parameters:
  LambdaName:
    Default: AWSReport
    Type: String
  Environment: 
    Default: DEV
    Type: String
  Sender:
    Default: [email protected]
    Type: String
  Recipient:
    Default: [email protected]
    Type: String
  Exceptions:
    Default: "TESTPRODUCT,ANOTHERTEST,Anothetest123"
    Type: String
  CodeBucket:
    Default: devopscfn
    Type: String
  S3Key: 
    Default: cleanup/cleanup.zip
    Type: String

Resources: 
  Role:
    Type: "AWS::IAM::Role"
    Properties:
      RoleName: !Sub '${LambdaName}-Role'
      Path: "/"     
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
          Action: sts:AssumeRole      
  RolePolicies:
    Type: "AWS::IAM::ManagedPolicy"
    Properties:
      ManagedPolicyName: !Sub '${LambdaName}-RolePolicies'
      Roles:
        - Ref: "Role"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:       
        - Effect: Allow
          Action:
          - ec2:describe*
          - cloudtrail:LookupEvents
          - autoscaling:Describe*
          - elasticloadbalancing:DescribeTags
          - config:PutEvaluations
          - rds:DescribeDBLogFiles
          - cloudwatch:GetMetricStatistics
          - support:*
          - trustedadvisor:*
          - elasticloadbalancing:DescribeLoadBalancers
          - rds:ListTagsForResource
          - rds:DownloadDBLogFilePortion
          - rds:DescribeDBInstances
          - elasticloadbalancing:DescribeInstanceHealth
          - redshift:DescribeClusters
          Resource:
          - '*'
        - Effect: Allow
          Action:
          - logs:CreateLogGroup
          - logs:CreateLogStream
          - logs:PutLogEvents
          Resource:
          - '*'
        - Effect: Allow
          Action:
          - config:PutEvaluations
          Resource:
          - '*'
        - Effect: Allow
          Action:
          - ses:SendEmail
          Resource:
          - '*'
  Lambda:          
    Type: "AWS::Lambda::Function"
    Properties: 
      Code:
        S3Bucket: !Ref CodeBucket
        S3Key: !Ref S3Key
      Description: "AWS Cleanup"
      FunctionName: !Sub '${LambdaName}Function'
      Handler: "main.lambda_handler"
      Timeout: 300
      Environment:
        Variables:
          "env": !Ref Environment
          "exceptions": !Ref Exceptions
          "sender": !Ref Sender
          "recipient": !Ref Recipient
      Role:
        Fn::GetAtt:
          - Role
          - Arn
      Runtime: "python3.6"
      Tags:
        -
          Key: "Name"
          Value: "Ops"
  ScheduledRule:
    Type: "AWS::Events::Rule"
    Properties:
      Name: !Sub '${LambdaName}-EventRule'
      Description: "ScheduledRule"
      ScheduleExpression: "rate(1 day)"
      State: "ENABLED"
      Targets:
      -
        Arn:
          Fn::GetAtt:
            - "Lambda"
            - "Arn"
        Id: "TargetFunction1"
  PermissionForEventsToInvokeLambda:
    Type: "AWS::Lambda::Permission"
    Properties:
      FunctionName: !Ref Lambda
      Action: "lambda:InvokeFunction"
      Principal: "events.amazonaws.com"
      SourceArn: !GetAtt ScheduledRule.Arn



EC2 Instances

Criteria :
EC2 instances that have had 10% or less daily average CPU utilization
and 5 MB or less network I/O on last 14 days

{% if ec2 %} {% for instance in ec2 %} {% for details in instance %} {% endfor %} {% endfor %}
Instance-Id Name Instance Type Cost CPU Network IO Days ProductName
{{ details }}
{% else %} No Instance matching the criteria {% endif %}

ELB

Criteria:
A load balancer has no active back-end instances.
A load balancer has no healthy back-end instances.

{% if elb %} {% for instance in elb %} {% for details in instance %} {% endfor %} {% endfor %}
ELB Name Reason Cost ProductName
{{ details }}
{% else %} No Instance matching the criteria {% endif %}

RDS Instances

Criteria:
An active DB instance has not had a connection in the last 7 days.

{% if rds %} {% for instance in rds %} {% for details in instance %} {% endfor %} {% endfor %}
Intance ID Instance Type Size Days Cost ProductName
{{ details }}
{% else %} No Instance matching the criteria {% endif %}

EBS Volumes

Criteria:
A volume is unattached

{% if ebs %} {% for instance in ebs %} {% for details in instance %} {% endfor %} {% endfor %}
Volume-Id Size Cost ProductName
{{ details }}
{% else %} No Volumes matching the criteria {% endif %}

Red Shift

Criteria:
A running cluster has not had a connection in the last 7 days.
A running cluster had less than 5% cluster-wide average CPU utilization for 99% of the last 7 days

{% if redshift %} {% for instance in redshift %} {% for details in instance %} {% endfor %} {% endfor %}
Name Instance Type Reason Cost ProductName
{{ details }}
{% else %} No Instance matching the criteria {% endif %}

Leave a Reply

Your email address will not be published.