0
votes

I'm trying to create a new EC2 instance using AWS JAVA API. But I get the following exception with message

Exception in thread "main" com.amazonaws.services.ec2.model.AmazonEC2Exception: Tag specification resource type must have a value (Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterValue; Request ID: XXXXXX)

public static void main(String[] args) {
    Ec2Utilities utils = new Ec2Utilities();
    Map<String, String> tagMap = new HashMap<String, String>();
    tagMap.put("name", "newinstance");
    tagMap.put("category", "cat1");
    utils.createInstanceFromAmi("t2.micro", "ami-sdfsds", 1, "sg-sdfsd", "nammme", tagMap);
}

public void createInstanceFromAmi(String instanceType, String amiId, int count, String securityGroup,
        String keyName, Map<String, String> tagMap) {
    AmazonEC2 ec2Client = Auth.getCredentails();
    TagSpecification tagSpecs = new TagSpecification();
    tagSpecs.setTags(buildTags(tagMap));
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withTagSpecifications(tagSpecs)
                                                                       .withInstanceType(instanceType)
                                                                       .withImageId(amiId)
                                                                       .withMinCount(count)
                                                                       .withMaxCount(2)
                                                                       .withSecurityGroupIds(securityGroup)
                                                                       .withKeyName(keyName);

    RunInstancesResult runInstances = ec2Client.runInstances(runInstancesRequest);

}

private List<Tag> buildTags(Map<String, String> tagMap) {
    List<Tag> tagList = new ArrayList<Tag>();
    tagMap.forEach((k, v) -> {
        tagList.add(new Tag(k, v));
    });
    System.out.println(tagList);
    return tagList;
}
2

2 Answers

0
votes

I fixed it myself. I added this

    List<TagSpecification> tagSpecifications = new ArrayList<>();
    tagSpecifications.add(new TagSpecification().withTags(buildTags(tagMap))

Where buildTags(tagMap) returns a `List'

0
votes

I ran into the same and found that to create a valid TagSpecification object for the RunInstanceRequest I needed to also set the resource type.

    TagSpecification resourceTags = new TagSpecification();
    resourceTags.setResourceType(ResourceType.Instance);

Once I did that I was able to create an instance with the tags I'd specified applied.