Skip to content

Instantly share code, notes, and snippets.

@djamelz
Created October 7, 2015 22:28
Show Gist options
  • Save djamelz/587f85a6487ef3fa2d1d to your computer and use it in GitHub Desktop.
Save djamelz/587f85a6487ef3fa2d1d to your computer and use it in GitHub Desktop.
Play with ec2 and java aws api.... Not the best way to do with scala (no future, tail rec vs. while...) but useful to have sync way to pop ec2 instances and kill them
import com.amazonaws.auth.{BasicAWSCredentials, InstanceProfileCredentialsProvider}
import com.amazonaws.services.ec2.AmazonEC2Client
import com.amazonaws.services.ec2.model._
import com.amazonaws.util.Base64
trait Ec2Utils extends Logging {
val AWS_ACCESS_KEY_ID: String
val AWS_SECRET_ACCESS_KEY: String
val instanceProfile = false
val endPoint = "ec2.us-west-1.amazonaws.com"
val instanceType = "m3.2xlarge"
val keyName = "dzouaoui-test"
val ami = "ami-df6a8b9b"
val securityGroup = "HighstrikerElasticSearch"
val instanceProfileRole = "aws-highstrikerES-role"
lazy val client = init()
def init() = {
val credentials = if (instanceProfile) new InstanceProfileCredentialsProvider().getCredentials else new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
val client = new AmazonEC2Client(credentials)
client.setEndpoint(endPoint)
client
}
def popElasticSearchInstance(): Instance = {
//This is call to pop a custom es 1.1 (see gist es.sh)
val userData = new String(Base64.encode(scala.io.Source.fromFile("es.sh").mkString.getBytes()))
popInstance(userData)
}
def popInstance(userData: String): Instance = {
val runInstancesRequest = new RunInstancesRequest().
withImageId(ami).
withInstanceType(instanceType).
withKeyName(keyName).
withMinCount(1).
withMaxCount(1).
withSecurityGroups(securityGroup).
withIamInstanceProfile(new IamInstanceProfileSpecification().withName(instanceProfileRole)).
withUserData(userData)
log.info("starting ec2 Instance...")
var instanceId = client.runInstances(runInstancesRequest).getReservation.getInstances.get(0).getInstanceId
log.info(s"ec2 Instance : Reservation done, Instance id:$instanceId, waiting for running state...")
val instance = waitingState(InstanceStateName.Running, instanceId)
log.info(s"ec2 Instance $instanceId running with private IP : ${instance.getPrivateIpAddress} and public IP : ${instance.getPublicIpAddress}")
instance
}
def killEc2Instance(instanceId: String) = {
client.terminateInstances(new TerminateInstancesRequest().withInstanceIds(instanceId))
log.info(s"Terminating ec2 instance $instanceId, waiting for terminated state...")
waitingState(InstanceStateName.Terminated, instanceId)
log.info(s"Ec2 instance $instanceId has been terminated")
}
def waitingState(state: InstanceStateName, instanceId: String): Instance = {
import scala.collection.JavaConversions._
def getStatusDetail() = client.describeInstanceStatus(new DescribeInstanceStatusRequest().withInstanceIds(instanceId)).getInstanceStatuses().map(x => x.getInstanceStatus.getDetails.map(y => y.getStatus)).flatten
var instance = client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceId)).getReservations.get(0).getInstances.get(0)
while (instance.getState.getName != state.toString) {
Thread sleep 10000
instance = client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instance.getInstanceId)).getReservations.get(0).getInstances.get(0)
log.info(s"ec2 Instance $instanceId waiting for the state : $state...")
}
if (state == InstanceStateName.Running) {
while (!getStatusDetail.contains("passed")) {
Thread sleep 30000
log.info(s"ec2 Instance $instanceId waiting for the end of initialization (passed instanceStatus)...")
}
}
log.info(s"ec2 Instance $instanceId : state $state OK !")
instance
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment