Guest User

Fernandoing 44 AWS lambda

a guest
Sep 17th, 2022
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #Politica Lambda:
  2. {
  3. "Version": "2012-10-17",
  4. "Statement": [
  5. {
  6. "Effect": "Allow",
  7. "Action": [
  8. "logs:CreateLogGroup",
  9. "logs:CreateLogStream",
  10. "logs:PutLogEvents"
  11. ],
  12. "Resource": "arn:aws:logs:*:*:*"
  13. },
  14. {
  15. "Effect": "Allow",
  16. "Action": [
  17. "ec2:DescribeInstances",
  18. "ec2:Start*",
  19. "ec2:Stop*"
  20. ],
  21. "Resource": "*"
  22. }
  23. ]
  24. }
  25.  
  26. #Funcion lambda python3
  27. import boto3
  28.  
  29.  
  30. region = 'us-east-1'
  31. ec2_client = boto3.client('ec2', region_name=region)
  32.  
  33. def lambda_handler(event, context):
  34. lambda_response = [] # Used for response of the lambda function
  35. instance_list = [] # Used for storing filtered instances
  36.  
  37. # Get a list of all instances filterd by tag
  38. response = ec2_client.describe_instances(Filters=[
  39. {
  40. 'Name': 'tag:Env',
  41. 'Values': ['dev']
  42. }
  43. ],
  44. )
  45.  
  46. # add found intances to instance_list
  47. for Reservation in response['Reservations']:
  48. for instance in Reservation['Instances']:
  49. print('Found ', instance['InstanceId'])
  50. instance_list.append(instance['InstanceId'])
  51.  
  52. # Turn off found instaces
  53. if len(instance_list) > 0:
  54. lambda_response.append(ec2_client.stop_instances(InstanceIds=instance_list))
  55. #pass
  56. else:
  57. lambda_response.append('No running instances found with given tag(s)')
  58. return lambda_response
Advertisement
Add Comment
Please, Sign In to add comment