export async function getInstancesByTag()

in src/aws/ec2Instances.ts [39:65]


export async function getInstancesByTag(tagKey: string, tagValue?: string): Promise<Instance[]> {
    console.log(`Finding EC2 instances that have tag ${tagKey}`);

    async function _getInstancesByTag(acc: Instance[] = [], nextToken?: string): Promise<Instance[]> {
        const req = new DescribeInstancesCommand({
            MaxResults: 1000,
            NextToken: nextToken,
            Filters: [
                { "Name": "instance-state-name", Values: ["running"] },
                { "Name": `tag${tagValue ? `:${tagKey}` : "-key"}`, Values: [tagValue || tagKey] }
            ]
        });

        const response = await awsEc2.send(req);

        const instances = buildInstances(response);
        const allInstances = acc.concat(instances);

        if(response.NextToken) {
            return await _getInstancesByTag(allInstances, response.NextToken);
        } else {
            return allInstances;
        }
    }

    return _getInstancesByTag();
}