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;
    }
}



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

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *