├── LambdaAndAutoscaling ├── auto_scaling_start_instances.py ├── auto_scaling_stop_instances.py └── rol ├── LambdaAndEC2 ├── EC2_start_instances.py ├── EC2_stop_instances.py └── rol ├── LambdaAndRDS ├── EC2_start_instances.py └── EC2_stop_instances.py ├── LambdaAndSpotFleet ├── Spot_start_instances.py ├── Spot_stop_instances.py ├── modificar spotfleet.JPG └── rol ├── README.md ├── callNextStep ├── awsPolitica └── index.js ├── cloudformation └── ApiGatewayAndLambda │ └── apiGatewayAndLambda.yml └── variableDeEntornos └── index.js /LambdaAndAutoscaling/auto_scaling_start_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuedas necesitas permisos sobre el lambda autoscaling:SetDesiredCapacity 4 | #************************************************* 5 | import boto3 6 | 7 | def lambda_handler(event, context): 8 | client = boto3.client('autoscaling') 9 | response = client.set_desired_capacity( 10 | AutoScalingGroupName='eks-workers-111111111111551110119000011111', 11 | DesiredCapacity=4 12 | ) -------------------------------------------------------------------------------- /LambdaAndAutoscaling/auto_scaling_stop_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuedas necesitas permisos sobre el lambda autoscaling:SetDesiredCapacity 4 | #************************************************* 5 | import boto3 6 | 7 | def lambda_handler(event, context): 8 | client = boto3.client('autoscaling') 9 | response = client.set_desired_capacity( 10 | AutoScalingGroupName='eks-workers-111111111111551110119000011111', 11 | DesiredCapacity=4 12 | ) -------------------------------------------------------------------------------- /LambdaAndAutoscaling/rol: -------------------------------------------------------------------------------- 1 | 2 | los permisos necesarios son los siguientes 3 | "autoscaling:SetDesiredCapacity" 4 | 5 | Necesitas crear algo similar al siguiente json dentro de IAM rol 6 | { 7 | "Version": "2012-10-17", 8 | "Statement": [ 9 | { 10 | "Effect": "Allow", 11 | "Action": "autoscaling:SetDesiredCapacity", 12 | "Resource": "*" 13 | } 14 | ] 15 | } 16 | 17 | -------------------------------------------------------------------------------- /LambdaAndEC2/EC2_start_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuedas necesitas permisos sobre el lambda startInstance y stopInstance 4 | #************************************************* 5 | import boto3 6 | 7 | import json 8 | 9 | region = 'us-east-1' 10 | 11 | instances = ['i-0f41e5678d34ec40e','i-0f41e5678d34ec40e','i-0f41e5678d34ec40e'] 12 | 13 | def lambda_handler(event, context): 14 | ec2 = boto3.client('ec2', region_name=region) 15 | ec2.start_instances(InstanceIds=instances) 16 | 17 | return { 18 | 'statusCode': 200, 19 | 'body': json.dumps('started your instances: ' + str(instances)) 20 | } 21 | -------------------------------------------------------------------------------- /LambdaAndEC2/EC2_stop_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuedas necesitas permisos sobre el lambda startInstance y stopInstance 4 | #************************************************* 5 | import boto3 6 | 7 | import json 8 | 9 | region = 'us-east-1' 10 | 11 | instances = ['i-0f41e5678d34ec40e','i-0f41e5678d34ec40e','i-0f41e5678d34ec40e'] 12 | 13 | def lambda_handler(event, context): 14 | ec2 = boto3.client('ec2', region_name=region) 15 | ec2.stop_instances(InstanceIds=instances) 16 | 17 | return { 18 | 'statusCode': 200, 19 | 'body': json.dumps('stop your instances: ' + str(instances)) 20 | } 21 | 22 | -------------------------------------------------------------------------------- /LambdaAndEC2/rol: -------------------------------------------------------------------------------- 1 | 2 | los permisos necesarios para son los siguientes 3 | "ec2:RebootInstances", 4 | "ec2:Start*", 5 | "ec2:Stop*" 6 | 7 | Necesitas crear algo similar al siguiente json dentro de IAM rol 8 | { 9 | "Version": "2012-10-17", 10 | "Statement": [ 11 | { 12 | "Effect": "Allow", 13 | "Action": [ 14 | "ec2:RebootInstances", 15 | "ec2:Start*", 16 | "ec2:Stop*" 17 | ], 18 | "Resource": "*" 19 | } 20 | ] 21 | } 22 | 23 | -------------------------------------------------------------------------------- /LambdaAndRDS/EC2_start_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuedas necesitas permisos sobre el lambda startInstance y stopInstance 4 | #************************************************* 5 | import boto3 6 | import json 7 | instances_rds = [''] 8 | 9 | def lambda_handler(event, context): 10 | rds = boto3.client('rds') 11 | for instance_rds in instances_rds: 12 | rds.start_db_instance(DBInstanceIdentifier = instance_rds) 13 | 14 | return { 15 | 'statusCode': 200, 16 | 'body': json.dumps('stops rds') 17 | } 18 | -------------------------------------------------------------------------------- /LambdaAndRDS/EC2_stop_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuerdas necesitas permisos sobre el lambda StopDBInstance y StartDBInstance 4 | #************************************************* 5 | import boto3 6 | import json 7 | instances_rds = [''] 8 | 9 | def lambda_handler(event, context): 10 | rds = boto3.client('rds') 11 | for instance_rds in instances_rds: 12 | rds.stop_db_instance(DBInstanceIdentifier = instance_rds) 13 | 14 | return { 15 | 'statusCode': 200, 16 | 'body': json.dumps('stops rds') 17 | } 18 | -------------------------------------------------------------------------------- /LambdaAndSpotFleet/Spot_start_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuedas necesitas permisos sobre el lambda startInstance y stopInstance 4 | #************************************************* 5 | import boto3 6 | 7 | import json 8 | region = 'us-east-1' 9 | 10 | def lambda_handler(event, context): 11 | ec2 = boto3.client('ec2', region_name=region) 12 | ec2.modify_spot_fleet_request( SpotFleetRequestId='sfr-1111111-1111-1111-1111-111111111111', 13 | TargetCapacity=1) 14 | return { 15 | 'statusCode': 200, 16 | 'body': json.dumps('started your instances: ') 17 | } 18 | -------------------------------------------------------------------------------- /LambdaAndSpotFleet/Spot_stop_instances.py: -------------------------------------------------------------------------------- 1 | #************************************************* 2 | # lambda_function.lambda_handler 3 | # recuedas necesitas permisos sobre el lambda startInstance y stopInstance 4 | #************************************************* 5 | import boto3 6 | 7 | import json 8 | region = 'us-east-1' 9 | 10 | def lambda_handler(event, context): 11 | ec2 = boto3.client('ec2', region_name=region) 12 | ec2.modify_spot_fleet_request( SpotFleetRequestId='sfr-1111111-1111-1111-1111-111111111111', 13 | TargetCapacity=0) 14 | return { 15 | 'statusCode': 200, 16 | 'body': json.dumps('stop your instances: ') 17 | } 18 | 19 | -------------------------------------------------------------------------------- /LambdaAndSpotFleet/modificar spotfleet.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/culturadevops/lambda-template/43e49db65e0ef996fe508d8912d8b401784987c8/LambdaAndSpotFleet/modificar spotfleet.JPG -------------------------------------------------------------------------------- /LambdaAndSpotFleet/rol: -------------------------------------------------------------------------------- 1 | 2 | los permisos necesarios para son los siguientes 3 | "ec2:DescribeSpotFleetRequests", 4 | "ec2:ModifySpotFleetRequest" 5 | 6 | Necesitas crear algo similar al siguiente json dentro de IAM rol 7 | { 8 | "Version": "2012-10-17", 9 | "Statement": [ 10 | { 11 | "Action": [ 12 | "ec2:DescribeSpotFleetRequests", 13 | "ec2:ModifySpotFleetRequest" 14 | ], 15 | "Effect": "Allow", 16 | "Resource": "*" 17 | } 18 | ] 19 | } 20 | 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lambda-template 2 | Recopilacion de codigo util sobre lambdas cloudformation,AWS SAM que puedas ver en culturadevops 3 | https://www.youtube.com/channel/UCfJ67eVA7DkKbbIF5ceJDMA?view_as=subscriber o https://culturadevops.blogspot.com/ 4 | 5 | 6 | 7 | 8 | Indice 9 | cloudformation de lambda y apigategay basico 10 | Apagar Instancias EC2 11 | Iniciar Instancias EC2 12 | Apagar Spot intance 13 | Iniciar Stop instance 14 | Apagar 15 | 16 | 17 | 18 | # Mis Libros: 19 | 20 | [![libros futuro es devops ](https://github.com/culturadevops/ecs_para_principiantes/blob/master/recursos/futuroesdevopsjaivicvillegas.png)](https://amzn.to/3S8AGG9) [![libros herramientas devops](https://github.com/culturadevops/ecs_para_principiantes/blob/master/recursos/herramientasdevops.png)](https://amzn.to/3ga1c4E) 21 | 22 | # Mi canal de cultura Devops 23 | 24 | [![canal de youtube sobre devops ](https://github.com/culturadevops/ecs_para_principiantes/blob/master/recursos/culturadevops.png)](https://www.youtube.com/channel/UCfJ67eVA7DkKbbIF5ceJDMA?sub_confirmation=1) -------------------------------------------------------------------------------- /callNextStep/awsPolitica: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "VisualEditor0", 6 | "Effect": "Allow", 7 | "Action": "lambda:InvokeFunction", 8 | "Resource": "arn:aws:lambda:*:*:function:*" 9 | } 10 | ] 11 | } -------------------------------------------------------------------------------- /callNextStep/index.js: -------------------------------------------------------------------------------- 1 | var AWS = require('aws-sdk'); 2 | AWS.config.update({region: 'us-east-1'}); 3 | var Lambda = new AWS.Lambda(); 4 | 5 | var NEXT_STEP_API = process.env.NEXT_STEP_API; 6 | 7 | function callNextStep(){ 8 | if (NEXT_STEP_API !== null && NEXT_STEP_API !== undefined) { 9 | console.log('invoking lambda', NEXT_STEP_API); 10 | Lambda.invoke({ 11 | FunctionName: NEXT_STEP_API, 12 | InvocationType: "Event" 13 | }, function(e, d) { 14 | if (e) { 15 | console.error("invocation error", JSON.stringify(e)); 16 | } else { 17 | console.log("invocation success", d); 18 | } 19 | }); 20 | } 21 | } 22 | 23 | exports.handler = (event, context, callback) => { 24 | context.callbackWaitsForEmptyEventLoop = false; 25 | callNextStep(); 26 | 27 | }; -------------------------------------------------------------------------------- /cloudformation/ApiGatewayAndLambda/apiGatewayAndLambda.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | 3 | Description: AWS API Gateway with a Lambda Integration 4 | 5 | Resources: 6 | 7 | ApiGatewayRestApi: 8 | Type: AWS::ApiGateway::RestApi 9 | Properties: 10 | ApiKeySourceType: HEADER 11 | Description: An API Gateway with a Lambda Integration 12 | EndpointConfiguration: 13 | Types: 14 | - EDGE 15 | Name: lambda-api 16 | 17 | ApiGatewayResource: 18 | Type: AWS::ApiGateway::Resource 19 | Properties: 20 | ParentId: !GetAtt ApiGatewayRestApi.RootResourceId 21 | PathPart: 'lambda' 22 | RestApiId: !Ref ApiGatewayRestApi 23 | 24 | ApiGatewayMethod: 25 | Type: AWS::ApiGateway::Method 26 | Properties: 27 | ApiKeyRequired: false 28 | AuthorizationType: NONE 29 | HttpMethod: POST 30 | Integration: 31 | ConnectionType: INTERNET 32 | Credentials: !GetAtt ApiGatewayIamRole.Arn 33 | IntegrationHttpMethod: POST 34 | PassthroughBehavior: WHEN_NO_MATCH 35 | TimeoutInMillis: 29000 36 | Type: AWS_PROXY 37 | Uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations' 38 | OperationName: 'lambda' 39 | ResourceId: !Ref ApiGatewayResource 40 | RestApiId: !Ref ApiGatewayRestApi 41 | 42 | ApiGatewayModel: 43 | Type: AWS::ApiGateway::Model 44 | Properties: 45 | ContentType: 'application/json' 46 | RestApiId: !Ref ApiGatewayRestApi 47 | Schema: {} 48 | 49 | ApiGatewayStage: 50 | Type: AWS::ApiGateway::Stage 51 | Properties: 52 | DeploymentId: !Ref ApiGatewayDeployment 53 | Description: Lambda API Stage v0 54 | RestApiId: !Ref ApiGatewayRestApi 55 | StageName: 'v0' 56 | 57 | ApiGatewayDeployment: 58 | Type: AWS::ApiGateway::Deployment 59 | DependsOn: ApiGatewayMethod 60 | Properties: 61 | Description: Lambda API Deployment 62 | RestApiId: !Ref ApiGatewayRestApi 63 | 64 | ApiGatewayIamRole: 65 | Type: AWS::IAM::Role 66 | Properties: 67 | AssumeRolePolicyDocument: 68 | Version: '2012-10-17' 69 | Statement: 70 | - Sid: '' 71 | Effect: 'Allow' 72 | Principal: 73 | Service: 74 | - 'apigateway.amazonaws.com' 75 | Action: 76 | - 'sts:AssumeRole' 77 | Path: '/' 78 | Policies: 79 | - PolicyName: LambdaAccess 80 | PolicyDocument: 81 | Version: '2012-10-17' 82 | Statement: 83 | - Effect: 'Allow' 84 | Action: 'lambda:*' 85 | Resource: !GetAtt LambdaFunction.Arn 86 | 87 | LambdaFunction: 88 | Type: AWS::Lambda::Function 89 | Properties: 90 | Code: 91 | ZipFile: | 92 | def handler(event, context): 93 | response = { 94 | 'isBase64Encoded': False, 95 | 'statusCode': 200, 96 | 'headers': {}, 97 | 'multiValueHeaders': {}, 98 | 'body': 'Hello, World!' 99 | } 100 | return response 101 | Description: AWS Lambda function 102 | FunctionName: 'lambda-function' 103 | Handler: index.handler 104 | MemorySize: 256 105 | Role: !GetAtt LambdaIamRole.Arn 106 | Runtime: python3.7 107 | Timeout: 60 108 | 109 | LambdaIamRole: -------------------------------------------------------------------------------- /variableDeEntornos/index.js: -------------------------------------------------------------------------------- 1 | exports.handler = async event => { 2 | //esta variable se podra visualizar en el log del lambda 3 | console.log("log:" + process.env.primeravariable); 4 | 5 | const response = { 6 | statusCode: 200, 7 | //Esta variable sera enviada en la respuesta que retorna el lambda 8 | body: JSON.stringify(process.env.primeravariable) 9 | }; 10 | return response; 11 | }; 12 | --------------------------------------------------------------------------------