Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


AWS Lambda to start an rds instance

April 22, 2019

AWS Lambda to start an ec2 instance

First you need to set up a role to execute Lambda functions and ec2 instance functions.

Second you need to get your ec2 instance ids.

Python 2.7

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g.; 'us-east-1'
region = 'us-west-2'
# Enter your instances here: ex. ['X-XXXXXXXX']
instances = ['i-057fc46fb31c7214e']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.start_instances(InstanceIds=instances)
    print 'started your instances: ' + str(instances)

Java 8

public class ActionHandler implements RequestHandler<Object, String> {
	
	AmazonEc2Service amazonEc2Service = new AmazonEc2Service();
	
	@Override
	public String handleRequest(Object input, Context context) {
		context.getLogger().log("Input: " + input);
		
		amazonEc2Service.startSilverInstances();
		
		return "Hello from Lambda!";
	}

}
public class AmazonEc2Service {

	private AwsConfig awsConfig;
	
	private final List<String> instanceIds = Arrays.asList("i-028f37b8a9749dd9a","i-057fc46fb31c7214e");

	public AmazonEc2Service() {
		awsConfig = new AwsConfig();
	}

	public void startSilverInstances() {
		System.out.println("startSilverInstances()");
		AmazonEC2 amazonEC2 = awsConfig.getAmazonEC2();
		
		
		StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceIds);
		
		ObjectNode msg = ObjectUtils.getObjectNode();

		StartInstancesResult result = amazonEC2.startInstances(startInstancesRequest);
		
		
		System.out.println("done startSilverInstances!");
	}
}
public class AwsConfig {
	
    private final String amazonAWSAccessKey = ""; 
    private final String amazonAWSSecretKey = "";  
    
    private AWSCredentialsProvider amazonAWSCredentialsProvider;
    
    
 
    public AwsConfig() { 
        amazonAWSCredentialsProvider = new AWSStaticCredentialsProvider(new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey));
    } 
    
    public AmazonEC2 getAmazonEC2() {
    	AmazonEC2 client = AmazonEC2ClientBuilder.standard().withCredentials(amazonAWSCredentialsProvider)
    	.withRegion(Regions.US_WEST_2).build();
    	
    	return client;
    }
}
April 22, 2019

AWS Lambda to stop an ec2 instance

 

First you need to set up a role to execute lambda functions and also ec2 instance functions.

Second you need to get your ec2 instance ids.

Python 2.7

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-west-2'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['i-028f37b8a9749dd9a']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)
    print 'stopped your instances: ' + str(instances)

Java 8

public class ActionHandler implements RequestHandler<Object, String> {
	
	AmazonEc2Service amazonEc2Service = new AmazonEc2Service();
	
	@Override
	public String handleRequest(Object input, Context context) {
		context.getLogger().log("Input: " + input);
		
		amazonEc2Service.stopSilverInstances();
		
		return "Hello from Lambda!";
	}

}
public class AmazonEc2Service {

	private AwsConfig awsConfig;
	
	private final List<String> ids = Arrays.asList("i-028f37b8a9749dd9a","i-057fc46fb31c7214e");

	public AmazonEc2Service() {
		awsConfig = new AwsConfig();
	}

	public void stopSilverInstances() {
		System.out.println("stopSilverInstances()");
		AmazonEC2 amazonEC2 = awsConfig.getAmazonEC2();
		
		StopInstancesRequest request = new StopInstancesRequest()
				.withInstanceIds(ids);
		
		ObjectNode msg = ObjectUtils.getObjectNode();

		StopInstancesResult result = amazonEC2.stopInstances(request);
		
		
		
		System.out.println("done stopSilverInstances!");
	}
}
public class AwsConfig {
	
	private final String amazonAWSAccessKey = ""; 
    private final String amazonAWSSecretKey = ""; 
    
    private AWSCredentialsProvider amazonAWSCredentialsProvider;
    
    
 
    public AwsConfig() { 
        amazonAWSCredentialsProvider = new AWSStaticCredentialsProvider(new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey));
    } 
    
    public AmazonEC2 getAmazonEC2() {
    	AmazonEC2 client = AmazonEC2ClientBuilder.standard().withCredentials(amazonAWSCredentialsProvider)
    	.withRegion(Regions.US_WEST_2).build();
    	
    	return client;
    }
}

Bring down ecs instances for off hours

#!/usr/bin/env python
"""
A Lambda Function to set the desired count of running tasks
in a service based on a cluster's containter instances.
Designed to be triggered by a CloudWatch Event rule.
"""
from __future__ import print_function

import os
import json
import boto3


def ecs_client():
    return boto3.client("ecs")


def adjust_service_desired_count(ecs_client, cluster, service, desiredCount):
    running_service = ecs_client.describe_services(cluster=cluster, services=[service])

    if not running_service["services"]:
        print("SKIP: Service not found in cluster {}".format(cluster))
        return

    desired_task_count = running_service["services"][0]["desiredCount"]

    clusters = ecs_client.describe_clusters(clusters=[cluster])
    registered_instances = clusters["clusters"][0]["registeredContainerInstancesCount"]

    if desired_task_count != desiredCount:
        print("Adjusting cluster '{}' to run {} tasks of service '{}'".format(
            cluster, desiredCount, service
        ))
        response = ecs_client.update_service(
            cluster=cluster,
            service=service,
            desiredCount=desiredCount,
        )

        print(response)
        return response

    # Do nothing otherwise
    print("SKIP: Cluster {} has {} desired tasks for {} registered instances.".format(
        cluster, desired_task_count, registered_instances
    ))
    return


def lambda_handler(event, context):
    cluster_service_mapping = {
        'api-cluster': [
          'arn:aws:ecs:us-east-1:{account-id}:service/api-auth-service',
          'arn:aws:ecs:us-east-1:{account-id}:service/api-account-service'
        ]
    }
        
    desired_count = int(os.getenv('DESIRED_COUNT'))
    
    for cluster, services in cluster_service_mapping.items():
        for service in services:
            adjust_service_desired_count(ecs_client(), cluster, service, desired_count)

    print("DONE")
    return {
        "statusCode": 200,
        "body": json.dumps({ "message": "success" })
    }
April 22, 2019

MySQL If

 

IF function

The IF function is used to evaluate an expression and return a value.

The IF function consists of three parts.
1. condition to evaluate.
2. expression(can be another IF function) or value if the condition is evaluated to true.
3. expression(can be another IF function) or value if the condition is evaluated to false.

IF(condition, if_true_expr_or_value, if_false_expr_or_value)

Our example above shows ‘no sales rep’ if the condition(sales_rep_id IS NULL) is true and ‘sales rep’ if false.

IF function with aggregate functions

Here we are summing up the number of customers with and without reps.

 

 

April 12, 2019

MySQL Explain

 

https://www.sitepoint.com/using-explain-to-write-better-mysql-queries/

 

April 10, 2019