Skip to content

Instantly share code, notes, and snippets.

@vipulraheja
Last active March 19, 2019 21:18
Show Gist options
  • Save vipulraheja/9101874 to your computer and use it in GitHub Desktop.
Save vipulraheja/9101874 to your computer and use it in GitHub Desktop.
/*
* Create an Amazon AWS Instance and Programmatically SSH into it
*/
/*
* Copyright 2010 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Modified by Sambit Sahu
* Modified by Kyung-Hwa Kim ([email protected])
*
*
*/
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupEgressRequest;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupResult;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.DescribeImagesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
import com.amazonaws.services.ec2.model.KeyPair;
import com.amazonaws.services.ec2.model.Image;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceState;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
public class AwsSample {
/*
* Important: Be sure to fill in your AWS access credentials in the
* AwsCredentials.properties file before you try to run this
* sample.
* http://aws.amazon.com/security-credentials
*/
static AmazonEC2 ec2;
public static void main(String[] args) throws Exception {
// Create and initialize an credentials instance
AWSCredentials credentials = new PropertiesCredentials(
AwsSample.class.getResourceAsStream("AwsCredentials.properties"));
/*********************************************
*
* #1 Create Amazon Client object
*
*********************************************/
System.out.println("#1 Create Amazon Client object");
ec2 = new AmazonEC2Client(credentials);
// Set End Point
ec2.setEndpoint("ec2.us-east-1.amazonaws.com");
/*********************************************
*
* #1.1 Describe EC2 Security Group.
*
*********************************************/
String groupName = "VR2337";
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();
createSecurityGroupRequest.withGroupName(groupName).withDescription("VR2337 Security Group");
ec2.createSecurityGroup(createSecurityGroupRequest);
/*********************************************
*
* #1.2 Describe Permissions.
*
*********************************************/
IpPermission ipPermission = new IpPermission();
// SSH Permissions
ipPermission.withIpRanges("0.0.0.0/0")
.withIpProtocol("tcp")
.withFromPort(22)
.withToPort(22);
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();
authorizeSecurityGroupIngressRequest.withGroupName(groupName).withIpPermissions(ipPermission);
ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
// HTTP Permissions
ipPermission = new IpPermission();
ipPermission.withIpRanges("0.0.0.0/0")
.withIpProtocol("tcp")
.withFromPort(80)
.withToPort(80);
authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();
authorizeSecurityGroupIngressRequest.withGroupName(groupName).withIpPermissions(ipPermission);
ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
/*********************************************
*
* #1.3 Create Key Pair.
*
*********************************************/
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();
String keyName = "VR2337.pem";
createKeyPairRequest.withKeyName(keyName);
CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);
KeyPair keyPair = new KeyPair();
keyPair = createKeyPairResult.getKeyPair();
String privateKey = keyPair.getKeyMaterial();
File keyFile = new File(keyName);
FileWriter fw = new FileWriter(keyFile);
fw.write(privateKey);
fw.close();
try {
/*********************************************
*
* #2 Describe Availability Zones.
*
*********************************************/
System.out.println("#2 Describe Availability Zones.");
DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() +
" Availability Zones.");
/*********************************************
*
* #3 Describe Available Images
*
*********************************************/
// System.out.println("#3 Describe Available Images");
// DescribeImagesResult dir = ec2.describeImages();
// List<Image> images = dir.getImages();
// System.out.println("You have " + images.size() + " Amazon images");
/*********************************************
*
* #4 Describe Key Pair
*
*********************************************/
System.out.println("#9 Describe Key Pair");
DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
System.out.println(dkr.toString());
/*********************************************
*
* #5 Describe Current Instances
*
*********************************************/
System.out.println("#4 Describe Current Instances");
DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
List<Reservation> reservations = describeInstancesRequest.getReservations();
Set<Instance> instances = new HashSet<Instance>();
// add all instances to a Set.
for (Reservation reservation : reservations) {
instances.addAll(reservation.getInstances());
}
System.out.println("You have " + instances.size() + " Amazon EC2 instance(s).");
for (Instance ins : instances){
// instance id
String instanceId = ins.getInstanceId();
// instance state
InstanceState is = ins.getState();
System.out.println(instanceId+" "+is.getName());
}
/*********************************************
*
* #6 Create an Instance
*
*********************************************/
System.out.println("#5 Create an Instance");
String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI
String instanceType="t1.micro"; //create a free micro instance
int minInstanceCount = 1; // create 1 instance
int maxInstanceCount = 1;
String publicDNS="";
String publicIP="";
/*** Run Instance ***/
RunInstancesRequest rir = new RunInstancesRequest();
rir.withImageId(imageId)
.withInstanceType(instanceType)
.withMinCount(minInstanceCount)
.withMaxCount(maxInstanceCount)
.withKeyName(keyName)
.withSecurityGroups(groupName);
RunInstancesResult result = ec2.runInstances(rir);
/***********to make sure the instance's state is "running instead of "pending",**********/
/***********we wait for a while **********/
System.out.println("waiting");
Thread.currentThread().sleep(180000);
System.out.println("OK");
//get instanceId from the result
List<Instance> resultInstance = result.getReservation().getInstances();
String createdInstanceId = null;
for (Instance ins : resultInstance){
createdInstanceId = ins.getInstanceId();
System.out.println("New instance has been created: "+ins.getInstanceId());
}
/*********************************************
*
* #6.5 print public DNS and IP *
*
*********************************************/
describeInstancesRequest = ec2.describeInstances();
reservations = describeInstancesRequest.getReservations();
instances = new HashSet<Instance>();
for (Reservation reservation : reservations) {
instances.addAll(reservation.getInstances());
//obtain public DNs of the instance that was just created
if(reservation.getInstances().get(0).getPrivateIpAddress()!= null &&
reservation.getInstances().get(0).getInstanceId().equals(createdInstanceId))
{
publicDNS = reservation.getInstances().get(0).getPublicDnsName();
publicIP = reservation.getInstances().get(0).getPublicIpAddress();
System.out.println("Public DNS: "+publicDNS);
System.out.println("Public IP: "+publicIP);
}
}
/*********************************************
*
* #7 Create a 'tag' for the new instance.
*
*********************************************/
System.out.println("#6 Create a 'tag' for the new instance.");
List<String> resources = new LinkedList<String>();
List<Tag> tags = new LinkedList<Tag>();
Tag nameTag = new Tag("Name", "InstanceFromEclipse_MiniHW2");
resources.add(createdInstanceId);
tags.add(nameTag);
CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
ec2.createTags(ctr);
/*********************************************
*
* #8 Stop/Start an Instance
*
*********************************************/
System.out.println("#7 Stop the Instance");
List<String> instanceIds = new LinkedList<String>();
instanceIds.add(createdInstanceId);
//stop
/* StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
ec2.stopInstances(stopIR);
System.out.println("waiting");
Thread.currentThread().sleep(50000);
System.out.println("OK");
//start
StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
ec2.startInstances(startIR);
System.out.println("waiting");
Thread.currentThread().sleep(50000);
System.out.println("OK.. connecting");
*/
connectToInstance(publicDNS, keyName);
System.out.println("waiting");
Thread.currentThread().sleep(30000);
System.out.println("OK");
/*********************************************
*
* #9 Terminate an Instance
*
*********************************************/
System.out.println("#8 Terminate the Instance");
TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
// ec2.terminateInstances(tir);
/*********************************************
*
* #10 shutdown client object
*
*********************************************/
ec2.shutdown();
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
}
}
/********************SECTION 2: SSH INTO THE INSTANCE**************************/
public static void connectToInstance(String publicDNS, String keyname) throws IOException
{
JSch jSch = new JSch();
try {
//Authenticate through .pem file
jSch.addIdentity(keyname);
//Give username and public dns to connect
//username is ec2-user for amazon linux ami
Session session = jSch.getSession("ec2-user", publicDNS, 22);
//Required if not a trusted host
java.util.Properties configuration = new java.util.Properties();
configuration.put("StrictHostKeyChecking", "no");
session.setConfig(configuration);
System.out.println("Connecting to new instance " + publicDNS + " via SSH....");
session.connect();
//Open a shell
Channel channel=session.openChannel("shell");
channel.setOutputStream(System.out);
//Create a Shell Script
File shellScript = createShellScript();
//Convert the shell script to byte stream
FileInputStream fin = new FileInputStream(shellScript);
byte fileContent[] = new byte[(int)shellScript.length()];
fin.read(fileContent);
InputStream in = new ByteArrayInputStream(fileContent);
//Set the shell script to the channel as input stream
channel.setInputStream(in);
//Connect
channel.connect();
}
catch (JSchException e) {
e.printStackTrace();
}
}
public static File createShellScript()
{
String filename = "basic_commands.sh";
File scriptFile = new File(filename);
try{
// Create file
PrintStream out = new PrintStream(new FileOutputStream(scriptFile));
out.println("echo \"Programmatically SSHed into the instance.\"");
out.println("pwd");
out.println("ls");
out.println("ps");
out.println("exit");
//Close the output stream
out.close();
}
catch (Exception e)
{
System.err.println("The following error occured: " + e.getMessage());
}
return scriptFile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment