Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. from __future__ import print_function
  2.  
  3. import json
  4. import boto3
  5.  
  6. # global
  7. nametags=['dev','prod'] # Some tags here
  8. ec2regions= ['eu-west-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-central-1', 'ap-northeast-2', 'ap-northeast-1', 'us-east-1', 'sa-east-1', 'us-west-1', 'us-west-2']
  9.  
  10. print('Loading function')
  11.  
  12. def lambda_handler(event, context):
  13. print("Received event: " + json.dumps(event, indent=2))
  14. result = stopec2()
  15. return result # Echo back the first key value
  16.  
  17. def stopec2():
  18. ec2 = boto3.resource('ec2');
  19. ret=[]
  20. count = 0;
  21.  
  22. for region in ec2regions:
  23. target=[]
  24. ec2 = boto3.resource('ec2',region);
  25. instances = ec2.instances.all()
  26. for instance in instances:
  27. ret.append({"Region": region, "id": instance.id})
  28. if instance.state['Name'] != 'running': continue
  29. if instance.tags is not None and any(tag['Key'] == 'Name' for tag in instance.tags):
  30. nametag = (tag['Value'] for tag in instance.tags if tag['Key'] == 'Name').next()
  31. if not nametag in nametags:
  32. count+=1
  33. target.append(instance)
  34. else:
  35. count+=1
  36. target.append(instance)
  37.  
  38. for instance in target:
  39. result = instance.stop()
  40. print (result)
  41. # stop all running instances we found
  42. print (count, "instances found")
  43. print (ret)
  44. return ret
  45.  
  46. # unused
  47. def getAllRegions():
  48. # get all regions
  49. ec2regions = []
  50. ec2client = boto3.client('ec2');
  51. regions = ec2client.describe_regions()
  52. for region in regions['Regions']:
  53. ec2regions.append(region['RegionName'])
  54. return ec2regions
  55.  
  56. # print (getAllRegions())
  57. # stopec2()
  58.  
  59. '''
  60. # lambda role policy to invoke this
  61. {
  62. "Version": "2012-10-17",
  63. "Statement": [
  64. {
  65. "Effect": "Allow",
  66. "Action": [
  67. "logs:CreateLogGroup",
  68. "logs:CreateLogStream",
  69. "logs:PutLogEvents",
  70. "ec2:*"
  71. ],
  72. "Resource": [
  73. "*"
  74. ]
  75. }
  76. ]
  77. }
  78. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement