serverless-tag-resources
Version:
Datamart: Tag all AWS resources with dual legacy + datamart:* tag support
79 lines (65 loc) • 2.17 kB
JavaScript
;
const {
EC2Client,
DescribeInstancesCommand,
DescribeAddressesCommand,
CreateTagsCommand,
} = require("@aws-sdk/client-ec2");
const { getClient, } = require("../aws-clients");
const { excludeAwsTags } = require("../tags");
/**
* Tag EC2 instance related resources: EBS volumes, ENIs, EIPs, Security Groups.
*/
async function tagEC2RelatedResources(config, resource, tags) {
const client = getClient(EC2Client, config);
const describeResult = await client.send(
new DescribeInstancesCommand({
InstanceIds: [resource.PhysicalResourceId],
})
);
const resourceIds = [];
for (const reservation of describeResult.Reservations || []) {
const ownerId = reservation.OwnerId;
for (const instance of reservation.Instances || []) {
// EBS Volumes
for (const bdm of instance.BlockDeviceMappings || []) {
if (bdm.Ebs && bdm.Ebs.VolumeId) {
resourceIds.push(bdm.Ebs.VolumeId);
}
}
// Network Interfaces
for (const eni of instance.NetworkInterfaces || []) {
resourceIds.push(eni.NetworkInterfaceId);
// Elastic IPs (only if owned by same account)
if (eni.Association && eni.Association.IpOwnerId === ownerId) {
const eipResult = await client.send(
new DescribeAddressesCommand({
PublicIps: [eni.Association.PublicIp],
})
);
for (const addr of eipResult.Addresses || []) {
resourceIds.push(addr.AllocationId);
}
}
// Security Groups
for (const sg of eni.Groups || []) {
resourceIds.push(sg.GroupId);
}
}
}
}
if (resourceIds.length > 0) {
// Use existing instance tags (excluding aws: reserved) as base
const instanceTags =
describeResult.Reservations?.[0]?.Instances?.[0]?.Tags || [];
const filteredTags = excludeAwsTags(instanceTags);
await client.send(
new CreateTagsCommand({
Resources: resourceIds,
Tags: filteredTags.length > 0 ? filteredTags : tags,
})
);
}
return resourceIds;
}
module.exports = { tagEC2RelatedResources };