AWS SDK Java Tagging Run Instances

63 Views Asked by At

Our AWS team enabled tags in INSTANCE and VOLUME and now we have to modify our codes to add tagging. I tried to tag an EC2 instance but I got the following error below and hopefully someone can point me in the right direction.

The Issue: The error is saying the instance or the volume is missing mandatory tags.

This is my sample code, if tagging is turned off this code will work.

try {
String accessKey = "XXXXXX";
String secretKey = "XXXXXX";
AwsBasicCredentials credentials = AwsBasicCredentials.create(accessKey, secretKey);

Ec2Client ec2 = Ec2Client.builder().region(Region.of("ca-central-1")).credentialsProvider(StaticCredentialsProvider.create(credentials)).build();

IamInstanceProfileSpecification iamSpec = IamInstanceProfileSpecification.builder().name("PROFILE1").build();

List<Tag> tags = new ArrayList<Tag>();

tags.add(Tag.builder().key("Department").value("IT").build());
tags.add(Tag.builder().key("Team").value("DEV").build());

TagSpecification tagSpecs = TagSpecification.builder()
.resourceType(ResourceType.VOLUME)
.resourceType(ResourceType.INSTANCE)
.tags(tags)
.build();

RunInstancesRequest runRequest = RunInstancesRequest.builder()
.imageId("ami-xxxxx")
.instanceType(InstanceType.C5_2_XLARGE)
.keyName("xxx")
.subnetId("subnet-xxxxx")
.iamInstanceProfile(iamSpec)
.securityGroupIds("sg-xxxxxxx")
.tagSpecifications(tagSpecs)
.maxCount(1).minCount(1).build();

RunInstancesResponse response = ec2.runInstances(runRequest);

if (response.sdkHttpResponse().isSuccessful()) {
System.out.println("Successful");
} else {
System.out.println("Not Successful");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
1

There are 1 best solutions below

0
Lexus On BEST ANSWER

Managed to resolved the issue by separating the volume and instance

TagSpecification tagVolume = TagSpecification.builder().resourceType(ResourceType.VOLUME).tags(tags).build();

TagSpecification tagInstance = TagSpecification.builder().resourceType(ResourceType.INSTANCE).tags(tags).build();

RunInstancesRequest runRequest = RunInstancesRequest.builder()
.imageId("ami-xxxxx")
.instanceType(InstanceType.C5_2_XLARGE)
.keyName("xxx")
.subnetId("subnet-xxxxx")
.iamInstanceProfile(iamSpec)
.securityGroupIds("sg-xxxxxxx")
.tagSpecifications(tagVolume, tagInstance)
.maxCount(1).minCount(1).build();