Search code examples
javaamazon-web-servicesamazon-ec2

How to provide name of the Instance while creating aws ec2 using java aws sdk


I am finding it very hard to figure out how to provide the name of ec2 instance while creating ec2 instance using Aws Java SDK.

I am using following method to create ec2 Instance-

  RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
            runInstancesRequest.withImageId(ec2Configuration.getImageId())
                    .withInstanceType(ec2Configuration.getInstanceType())
                    .withMinCount(ec2Configuration.getMincount())
                    .withMaxCount(ec2Configuration.getMaxcount())
                    .withKeyName(ec2Configuration.getKeyPairName())
                    .withSecurityGroupIds(Arrays.asList(ec2Configuration.getSgId()));
            if (ec2Configuration.isEbsOptimized())
                runInstancesRequest.withMonitoring(true);
            if (ec2Configuration.isEbsOptimized())
                runInstancesRequest.withEbsOptimized(true);
            try {
                RunInstancesResult result = amazonEC2Client.runInstances(
                        runInstancesRequest);
                } catch (Exception e) {
                // all exception stuffs
                }

I could not find anything anywhere like .withName("myVmName").withInstanceType(...) or .define("myVmName").withInstanceType().

What is the way to set the name of Instance while creating an instance.

I want to give name given like the name 'cpanel' given in this image

Check this image.


Solution

  • Instances do not have a name, they instead have tags which are MetaData key values that are attached to the instance.

    You will have a tag with the key of "Name".

    What you would want to be looking at is the withTagSpecifications argument.