Amazon Web Service Java SDK Tutorial: Simplest Hello World

I looked at Amazon Web Services SDK a while back and started to work with it recently. While searching it the Internet, I got all the results on the first two pages on Google pointing back to Amazon, which is great. After reading these documents, however, I got headaches. Why? For one thing, they are pretty long and sometimes run over different Web pages. Do you want to read for an hour to get your first program running? Or you are like me who would like to get my first program like Hello World to run in 5 minutes or even shorter. We should then read more if we don’t understand some parts. If you have gone through the Amazon documents, you’d know it’s impossible.

After spending some time to go through the pain, I got a few samples running. To help other avoid the same pain, I’d like to share a very simple program that you can copy/paste to your IDE, modify to your keys, and run it within 2 minutes. I think this is probably the simplest and easier sample you can find on the Internet, but still does something meaningful – lists all the Amazon EC2 instances under your name, and print out their instance ID, public IP address, etc.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

Here are the code itself and the Maven pom.xml file. You can copy the code and pom.xml to your IDE project. Go to your Amazon account and get your access key and secret key (more details in the end of this post), then replace the key place holders I have in the source code (Don’t show your source to others or check in the source code to source control system afterwards). You should be able to run and got console output as shown in the end. You can of course print out more information from the the instance object.

package org.doublecloud.awssample;
 
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
 
public class AwsEc2HelloWorld
{
  public static void main(String[] args) throws Exception
  {
    AWSCredentials credentials = new BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY> - the longer one");
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
 
    DescribeInstancesResult insResult = ec2.describeInstances();
 
    int count = 1;
    for (Reservation reservation : insResult.getReservations())
    {
      for(Instance instance : reservation.getInstances())
      {
        System.out.println("Instance # " + count++
                + "\n InstanceId: " + instance.getInstanceId()
                + "\n InstanceType: " + instance.getInstanceType()
                + "\n Public IP: " + instance.getPublicIpAddress());
      }
    }
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.doublecloud</groupId>
    <artifactId>AwsEc2HelloWorld</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-ec2</artifactId>
            <version>1.10.50</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
</project>

Here is the console output. Yours might varies in instance numbers and values.

Instance # 1
 InstanceId: i-71fbfb81
 InstanceType: t2.micro
 Public IP: 52.91.118.8

I have a few other samples that covers other use cases. There we will save the access key and secret key in a property file so that you can hide it. Stay tuned …

How to Generate Access Key with AWS Console

To get your access and secret keys, you can login into your AWS console:

https://console.aws.amazon.com

On the top right, you should see your account name followed by region and support menu. Click on your account name for sub menus, and pick “Security Credentials.” You will be asked with two options “Continue to Security Credentials” and “Get Started with IAM Users”. Just select the first one and you will see a list of expandable list items. Expand the “Access Keys (Access Key ID and Secret Access Key)” and you should see list of existing keys, which can only be marked inactive or deleted. You can use “Create New Access Key” to get a dialogue box from where you can either “Show Access Key” or “Download Key File.” If you click on the first one, you will be shown both of the key values. Just copy and paste them.

If you choose to download them, that is fine too. In either case, you make sure to keep them safe.

This entry was posted in Cloud Computing, Software Development and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted June 15, 2016 at 7:01 am | Permalink

    Great post, most informative, didn’t realise amazon were into this.

  2. Posted November 8, 2016 at 5:09 am | Permalink

    We are Web design company offering quality Website Design, Website development, digital marketing, graphic design of sites for small to corporate level.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.