title: AWS - Automatic remediation of EC2s with Public IP
body: <p>Looking develop a python script that will scan EC2 instances for Public IP's and if found, stop those instances. </p>
  
  <p>I'm sorta new to Python so have challenges trying to put two pieces of code together. </p>
  
  <pre><code>
  ec2Resource = boto3.resource('ec2')
  def lambda_handler(event, context):
          instances = ec2Resource.instances.all()
          for instance in instances:
              #print("inst.public_ip_address",inst.public_ip_address)
              if instance.public_ip_address:
                  print("Instance ID: ",instance.id," , Instance Platform: ",instance.platform," , Public IP: ",instance.public_ip_address,", Instance Type:",instance.instance_type,",Instance Image Id: ",instance.image.id) 
  response = client.stop_instances(
      InstanceIds=[
          'string',
      ],
      Hibernate=True,
      DryRun=False,
      Force=False
  )
  </code></pre>
  
  <p>Basically, looking for a automated script that discovers public IPs on EC2's and then stops them. My apologies if the script above looks hamburglar</p>
  
  <p>UPDATE:
  Think I cleaned it up to create lists and then from that list, issue a stop.</p>
  
  <pre><code>#!/usr/bin/python
  '''
      Finds instance id, Instance Platform, Public IP, instance type based on tags.
      Returns a list of instances found
  '''
  
  import boto3
  
  def instances_find(name, value):
      '''
      Finds instance id's based on tags.
      Returns a list of instances found.
      '''
      list_instances = []
      # filter based on tags
      filters =[
          {
          'Name': name,
          'Values': [
              value,
              ]
          },
      ]
      instances = ec2_resource.instances.filter(Filters=filters)
      for instance in instances:
          # for each instance, append to list
          list_instances.append("Instance ID: ",instance.id," , Instance Platform: ",instance.platform," , Public IP: ",instance.public_ip_address,", Instance Type:",instance.instance_type,",Instance Image Id: ",instance.image.id)
      return list_instances
  
  def instances_stop(list):
      '''
      Stops instances defined in the list.
      '''
      ec2_client.stop_instances(InstanceIds=list)
  
  # enter tag name and value
  tag_name = 'tag:environment'
  tag_value = 'dev'
  
  ec2_resource = boto3.resource('ec2')
  ec2_client = boto3.client('ec2')
  
  # find instances
  ec2_list = instances_find(tag_name, tag_value)
  # stop instances
  ec2_stop = instances_stop(ec2_list)
  print('stopped instances: ' + str(ec2_list))
  
  </code></pre>