I am back with some more exciting information on Amazon. In my previous blog, I talked about AWS EC2 Console. This time, let’s talk about AWS Cloud SDKs, another AWS tool that will help you create an instance from your applications on the fly.
Prerequisites
Creating a new Virtual Server on the fly using AWS Cloud SDKs
You can create an Instance (Virtual Server) using AWS Cloud SDKs very easily. All you have to do is, use the below code snippets in your application.
Using AWS JAVA SDK:
// import required packages
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.Placement;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupResult;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import java.util.ArrayList;
import java.util.Collection;
// initialize ec2
AmazonEC2 ec2 = new AmazonEC2Client(new BasicAWSCredentials(
"AWS_ACCESS_KEY", "AWS_SECRET_KEY"));
// To create an instance following parameters are needed
// End_Point: the region where you want your instance to be created.
// e.g, ec2.ap-southeast-1.amazonaws.com
// AMI_ID: image id which is used to create the instance.
// Instance_Type: size of the Instance. e.g, t1.micro, m1.small
//Min_Count: minimum count for the instance (Integer).
// Max_Count: maximum count for the instance (Integer).
// Availability_Zone: the zone in which you want to create
// the instance. e.g, us-east-1d, us-east-1a
// Key_Name: the name of the key pair.
// Security_Group_Id: the id of the created security group.
// set the AWS region you want your instance to be created.
ec2.setEndpoint("End_Point");
// create Run Instance Request
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
// set the Run Instance Request parameters.
runInstancesRequest.withImageId("AMI_ID");
runInstancesRequest.withInstanceType("Instance_Type");
runInstancesRequest.withMinCount(Min_Count);
runInstancesRequest.withMaxCount(Max_Count);
// Placement parameter is used to set the availability zone in
// Run Instance Request.
Placement placement = new Placement();
placement.setAvailabilityZone("Availability_Zone");
runInstancesRequest.withPlacement(placement);
runInstancesRequest.withKeyName("Key_Name");
runInstancesRequest = runInstancesRequest
.withSecurityGroupIds("Security_Group_Id");
// if Disable Api Termination is set true, then you can't terminate
// the instance using the Amazon EC2 console, CLI, or API;
runInstancesRequest.withDisableApiTermination(true);
RunInstancesResult result = null;
try {
// create instance call
result = ec2.runInstances(runInstancesRequest);
System.out.println("Result: " + result.toString());
} catch (AmazonServiceException serviceEx) {
// handle service exception here
} catch (AmazonClientException clientEx) {
// handle client exception here
}
// To create Security Group
CreateSecurityGroupRequest sgReq = new CreateSecurityGroupRequest();
sgReq.withGroupName("YOUR_SECURITY_GROUP_NAME");
sgReq.withDescription("YOUR_SECURITY_GROUP_DESCRIPTION);
CreateSecurityGroupResult result = ec2.createSecurityGroup(sgReq);
// add rules to your created security group
Collection ipList = new ArrayList();
IpPermission ipPermission = new IpPermission();
Collection ipRange = new ArrayList();
ipRange.add("0.0.0.0/0");
ipPermission.setFromPort(80);
ipPermission.setIpProtocol("tcp");
ipPermission.setToPort(80);
ipPermission.setIpRanges(ipRange);
ipPermissionList.add(ipPermission);
AuthorizeSecurityGroupIngressRequest sgAuthRequest =
new AuthorizeSecurityGroupIngressRequest();
sgAuthRequest.withGroupName("SECURITY_GROUP_NAME");
sgAuthRequest.withIpPermissions(ipPermissionList);
ec2.authorizeSecurityGroupIngress(sgAuthRequest);
For further documentation on AWS JAVA SDK, click here
Using AWS PHP SDK:
// include the SDK using the Composer autoloader
require 'vendor/autoload.php';
use Aws\Ec2\Ec2Client;
// initialize ec2 client
$client = Ec2Client::factory(array(
'key' => 'AWS_ACCESS_KEY',
'secret' => 'AWS_SECRET_KEY',
'region' => 'AWS_REGION'
));
// To create an instance following parameters are needed
//AWS_REGION: the region where you want your instance to be created.
// e.g, ap-southeast-1
// AMI_ID: image id which is used to create the instance.
// Instance_Type: size of the Instance. e.g, t1.micro, m1.small
// Min_Count: minimum count for the instance (Integer).
// Max_Count: maximum count for the instance (Integer).
// Availability_Zone: the zone in which you want to create
// the instance. e.g, us-east-1d, us-east-1a
// Key_Name: the name of the key pair.
// Security_Group_Id: the id of the created security group.
// set the parameters.
try{
$result = $client->runInstances(array(
'ImageId' => 'AMI_ID',
'MinCount' => Min_Count,
'MaxCount' => Max_Count,
'KeyName' => 'Key_Name',
'SecurityGroupIds' => array('Security_Group_Id'),
'InstanceType' => 'Instance_Type',
'Placement' => array(
'AvailabilityZone' => 'Availability_Zone',
),
'DisableApiTermination' => true,
));
} catch(Exception $e){
print_r("Exception".$e);
}
// to create security group and add rules
$sgResult = $client->createSecurityGroup(array(
'GroupName' => 'YOUR_SECURITY_GROUP_NAME',
'Description' => 'YOUR_SECURITY_GROUP_DESCRIPTION',
));
$sgAuthResult = $client->authorizeSecurityGroupIngress(array(
'GroupName' => 'YOUR_SECURITY_GROUP_NAME',
'IpPermissions' => array(
array(
'IpProtocol' => 'tcp',
'FromPort' => 80,
'ToPort' => 80,
'IpRanges' => array(
array(
'CidrIp' => '0.0.0.0/0',
)
),
)
),
));
For further documentation on AWS PHP SDK, click here.
Using AWS RUBY SDK:
require 'rubygems'
require 'aws-sdk'
// initialize ec2
ec2 = AWS::EC2.new(
:access_key_id => 'Aws_Access_Key',
:secret_access_key => 'Aws_Secret_Key',
:ec2_endpoint => 'End_Point')
// To create an instance following parameters are needed
// End_Point: the region where you want your instance to be created.
// e.g, ec2.ap-southeast-1.amazonaws.com
// AMI_ID: image id which is used to create the instance.
// Instance_Type: size of the Instance. e.g, t1.micro, m1.small
// count: How many instances to request (Integer).
// Availability_Zone: the zone in which you want to create
// the instance. e.g, us-east-1d, us-east-1a
// Key_Name: the name of the key pair.
// Security_Group_Id: the id of the created security group.
// set the parameters.
instance_result = ec2.instances.create(
:image_id => 'AMI_ID',
:count => count,
:instance_type => 'Instance_Type',
:key_name => 'Key_Name',
:security_group_ids => 'Security_Group_Id',
:disable_api_termination => true,
:availability_zone => 'Availability_Zone'
)
// to create security group and add rules
security_group = ec2.security_groups.create(
'YOUR_SECURITY_GROUP_NAME')
ip_addresses = ['53.234.132.12/0', '57.23.112.34/0']
security_group.authorize_ingress :tcp, 22, *ip_addresses
// to create a key pair
key_pair = ec2.key_pairs.create('YOUR_KEY_PAIR_NAME')
For further documentation on AWS RUBY SDK, click here
In this post, I have explained the process of creating and managing Virtual Servers on Amazon using AWS Cloud SDKs.
If you have queries or need any further assistance, do write to us at support@shephertz.com
Leave A Reply