(Quick Reference)

4 Amazon Web Service - Reference Documentation

Authors: Benoit Hediard

Version: 1.9.40

4 Amazon Web Service

Reference amazonWebService from any of your Grails artefacts (controllers, domain, services...) to automatically inject it.

def amazonWebService

Or get it from ctx if you want to test it in Grails console.

def amazonWebService = ctx.amazonWebService

You can then access any services directly from amazonWebService.

// Available service clients
amazonWebService.autoScaling
amazonWebService.cloudFormation
amazonWebService.cloudFront
amazonWebService.cloudSearch
amazonWebService.cloudSearchDomain
amazonWebService.cloudTrail
amazonWebService.cloudWatch
amazonWebService.codeDeploy
amazonWebService.cognitoIdentity
amazonWebService.cognitoSync
amazonWebService.config
amazonWebService.dynamoDB
amazonWebService.dynamoDBMapper
amazonWebService.ec2
amazonWebService.elasticBeanstalk
amazonWebService.elasticLoadBalancing
amazonWebService.elasticMapreduce
amazonWebService.elasticTranscoder
amazonWebService.elastiCache
amazonWebService.glacier
amazonWebService.iam
amazonWebService.importExport
amazonWebService.kinesis
amazonWebService.kms
amazonWebService.opsWorks
amazonWebService.rds
amazonWebService.redshift
amazonWebService.route53
amazonWebService.s3
amazonWebService.s3Encryption
amazonWebService.ses
amazonWebService.sdb
amazonWebService.sns
amazonWebService.sqs
amazonWebService.sqsBufferedAsync
amazonWebService.storageGateway
amazonWebService.swf
amazonWebService.transferManager

It will return an instance of Java client class extending AmazonWebServiceClient with default region endpoint (defined in our Config.groovy).

You can then call any available client methods.

To know available methods for each service clients, check the latest version of online AWS SDK Java docs

Custom region

If required, you can pass the region name, to get a client with a different region endpoint.

// Use SQS for region 'eu-west-1'
amazonWebService.getSqs('eu-west-1').sendMessage(new SendMessageRequest(queueUrl, messageBody))

Async clients

If required, you can also get asynchronous client (which return Future on each async methods).

// Get async client
amazonWebService.sqsAsync.sendMessageAsync(new SendMessageRequest(queueUrl, messageBody))
// Get async client for region 'eu-west-1'
amazonWebService.getSqsAsync('eu-west-1').sendMessageAsync(new SendMessageRequest(queueUrl, messageBody))

Exception handling

You should surround all your amazonWebService client calls around try/catch block, in order to catch AmazonServiceException or AmazonClientException.

4.1 EC2 example

Start an EC2 t1.micro instance with Amazon Linux in eu-west1.

import com.amazonaws.services.ec2.model.*

// If your default region is eu-west-1 def reservation = amazonWebService.ec2.runInstances(new RunInstancesRequest('ami-fd231b89', 1, 1).withInstanceType('t1.micro')) // Or if your default region is not eu-west-1 (this ami ID is only runnable eu-west-1) def reservation = amazonWebService.getEc2('eu-west-1').runInstances(new RunInstancesRequest('ami-fd231b89', 1, 1).withInstanceType('t1.micro'))

List all your EC2 instances.

List reservations = amazonWebService.ec2.describeInstances().reservations
reservations.each { Reservation reservation ->
    println "reservationId: ${reservation.reservationId}"
    reservation.instances.each() { Instance instance ->
        println "instanceId: ${instance.instanceId}, imageId: ${instance.imageId}, instanceType: ${instance.instanceType}"
    }

}

Stop an EC2 instance.

amazonWebService.ec2.stopInstances(new StopInstancesRequest([instanceId]))

Terminate an EC2 instance.

amazonWebService.ec2.terminateInstances(new TerminateInstancesRequest([instanceId]))

Java doc

To know available methods for EC2 client, check AmazonEC2Client Java doc

4.2 RDS example

Start a RDS instance.

import com.amazonaws.services.rds.model.*

DBInstance dbInstance = amazonWebService.rds.createDBInstance(new CreateDBInstanceRequest('mydbserver', 5, 'db.t1.micro', 'MySQL', 'admin', 'password'))

List all your RDS instances.

List dbInstances = amazonWebService.rds.describeDBInstances().DBInstances
dbInstances.each { DBInstance dbInstance ->
    println "DBInstanceIdentifier: ${dbInstance.DBInstanceIdentifier}, DBInstanceStatus: ${dbInstance.DBInstanceStatus}, engine: ${dbInstance.engine}, allocatedStorage: ${dbInstance.allocatedStorage}"

}

Snapshot a RDS instance.

amazonWebService.rds.createDBSnapshot(new CreateDBSnapshotRequest('someSnapshot', 'mydbserver'))

Terminate a RDS instance without final snapshot.

amazonWebService.rds.deleteDBInstance(new DeleteDBInstanceRequest('mydbserver').withSkipFinalSnapshot(true))

Java doc

To know available methods for RDS client, check AmazonRDSClient Java doc

4.3 S3 example

Create a bucket.

import com.amazonaws.services.s3.model.*

// Bucket will be created in default config region amazonWebService.s3.createBucket('some-grails-bucket')

List buckets.

List buckets = amazonWebService.s3.listBuckets()
buckets.each { Bucket bucket ->
    println "bucketName: ${bucket.name}, creationDate: ${bucket.creationDate}"
}

List bucket files.

ObjectListing objectListing = amazonWebService.s3.listObjects('some-grails-bucket')
objectListing.objectSummaries.each { S3ObjectSummary summary ->
    println "key: ${summary.key}, lastModified: ${summary.lastModified}, size: ${summary.size}"
}

Upload a file with public read permissions.

amazonWebService.s3.putObject(new PutObjectRequest('some-grails-bucket', 'somePath/someKey.jpg', new File('/Users/ben/Desktop/photo.jpg')).withCannedAcl(CannedAccessControlList.PublicRead))

Download a file.

amazonWebService.s3.getObject(new GetObjectRequest('some-grails-bucket', 'somePath/someKey.jpg'), new File('/Users/ben/Downloads/photo.jpg'))

Delete a file.

amazonWebService.s3.deleteObject('some-grails-bucket', 'somePath/someKey.jpg')

Transfer manager

TransferManager provides a simple API for uploading content to Amazon S3, and makes extensive use of Amazon S3 multipart uploads to achieve enhanced throughput, performance and reliability.

Upload asynchronously a file with public read permissions.

import com.amazonaws.services.s3.model.CannedAccessControlList
import com.amazonaws.services.s3.transfer.*

PutObjectRequest putObjectRequest = new PutObjectRequest('some-grails-bucket', 'somePath/someKey.jpg', new File('/Users/ben/Desktop/photo.jpg')).withCannedAcl(CannedAccessControlList.PublicRead) Upload upload = amazonWebService.transferManager.upload(putObjectRequest)

while (!upload.done) { println "Transfer: $upload.description" println " - State: $upload.state" println " - Progress: $upload.progress.bytesTransfered" // Do work while we wait for our upload to complete… Thread.sleep(500) }

Upload asynchronously multiple files from a directory.

MultipleFileUpload upload = amazonWebService.transferManager.uploadDirectory('some-grails-bucket', 'some-virtual-directory', new File('/Users/ben/Desktop/SomeDirectory'), false)

while (!upload.done) { println "Transfer: $upload.description" println " - State: $upload.state" println " - Progress: $upload.progress.bytesTransfered" // Do work while we wait for our upload to complete… Thread.sleep(500) }

Download asynchronously a file.

Download download = amazonWebService.transferManager.download(new GetObjectRequest('some-grails-bucket', 'somePath/someKey.jpg'),  new File('/Users/ben/Downloads/photo.jpg'))

while (!download.done) { println "Transfer: $download.description" println " - State: $download.state" println " - Progress: $download.progress.bytesTransfered" // Do work while we wait for our upload to complete… Thread.sleep(500) }

Download asynchronously multiple files.

MultipleFileDownload download = amazonWebService.transferManager.downloadDirectory('some-grails-bucket', 'some-virtual-directory',  new File('/Users/ben/Downloads'))

while (!download.done) { println "Transfer: $download.description" println " - State: $download.state" println " - Progress: $download.progress.bytesTransfered" // Do work while we wait for our upload to complete… Thread.sleep(500) }

Note: you might want to increase S3 connection timeout config parameter for large uploads/downloads.

Java doc

To know available methods for S3 client, check AmazonS3Client Java doc

To know available methods for S3 transfer manager, check TransferManager Java doc

4.4 SES example

SES is currently only available in some region (us-east-1, us-west-2, eu-west-1), so you might define it in your config if required or use amazonWebService.getSes('us-east-1').

Verifies an email address (send a confirmation email).

import com.amazonaws.services.simpleemail.model.*

amazonWebService.ses.verifyEmailIdentity(new VerifyEmailIdentityRequest().withEmailAddress('notification@mydomain.com'))

List verified address.

List emailAddresses = amazonWebService.ses.listVerifiedEmailAddresses().verifiedEmailAddresses
emailAddresses.each {
    println it
}

Send an email.

String source = 'notification@mydomain.com'
Destination destination = new Destination(['myemail@gmail.com'])
Content subject = new Content('Some subject...')
Body body = new Body().withHtml(new Content('''Hi,<br />
<br />
Some <b>HTML</b> body…
'''))
Message message = new Message(subject, body)
amazonWebService.ses.sendEmail(new SendEmailRequest(source, destination, message))

Get send statistics

GetSendStatisticsResult statistics = amazonWebService.ses.getSendStatistics()
statistics.sendDataPoints.each { SendDataPoint sendDataPoint ->
    println "bounces=${sendDataPoint.bounces}, complaints=${sendDataPoint.complaints}, deliveryAttempts=${sendDataPoint.deliveryAttempts}, rejects=${sendDataPoint.rejects}"
}

Get send quota

GetSendQuotaResult quota = amazonWebService.ses.getSendQuota()
println "max24HourSend: ${quota.max24HourSend}, sentLast24Hours: ${quota.sentLast24Hours}, sentLast24Hours: ${quota.sentLast24Hours}"

Java doc

To know available methods for SES client, check AmazonSimpleEmailServiceClient Java doc

4.5 SQS example

Create a queue.

import com.amazonaws.services.sqs.model.*

String queueUrl = amazonWebService.sqs.createQueue(new CreateQueueRequest('someQueue')).queueUrl

Send a message

amazonWebService.sqs.sendMessage(new SendMessageRequest(queueUrl, 'Some message...'))

Receive and delete messages

List messages = amazonWebService.sqs.receiveMessage(new ReceiveMessageRequest(queueUrl)).messages
messages.each { Message message ->
    println "id: ${message.messageId}, body: ${message.body}"
    amazonWebService.sqs.deleteMessage(new DeleteMessageRequest(queueUrl, message.receiptHandle))
}

Delete a queue.

amazonWebService.sqs.deleteQueue(new DeleteQueueRequest('someQueue'))

Java doc

To know available methods for SQS client, check AmazonSQSClient Java doc

4.6 Other services

For other services, check the Java doc :