-
-
Save JakeGinnivan/c40c24b93463ea5949ce441a21a8a0f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as pulumi from '@pulumi/pulumi' | |
import AWS from 'aws-sdk' | |
import ELBv2 from 'aws-sdk/clients/elbv2' | |
import cuid from 'cuid' | |
export interface SharedLoadBalancer { | |
albArn: string | |
albDnsName: string | |
albZoneId: string | |
webListernerArn: string | |
} | |
interface LeastUsedLoadBalancerProviderInputs { | |
awsRegion: string | |
assumeRole?: string | |
loadBalancerArnsToCheck: SharedLoadBalancer[] | |
} | |
const leastUsedLoadBalancerProvider: pulumi.dynamic.ResourceProvider = { | |
async create({ | |
awsRegion, | |
assumeRole, | |
loadBalancerArnsToCheck, | |
}: LeastUsedLoadBalancerProviderInputs) { | |
const elb = new ELBv2({ | |
region: awsRegion, | |
credentials: assumeRole | |
? new AWS.TemporaryCredentials({ | |
RoleSessionName: 'LeastUsedLoadBalancer', | |
RoleArn: assumeRole, | |
}) | |
: undefined, | |
}) | |
const listenerWithRules = await Promise.all( | |
loadBalancerArnsToCheck.map(async (loadBalancer) => { | |
return { | |
loadBalancer, | |
rules: await elb | |
.describeRules({ | |
ListenerArn: loadBalancer.webListernerArn, | |
PageSize: 100, | |
}) | |
.promise(), | |
} | |
}), | |
) | |
const sorted = listenerWithRules.sort((a, b) => { | |
return (a.rules.Rules?.length || 0) - (b.rules.Rules?.length || 0) | |
}) | |
pulumi.log.info(`Load balancers: | |
${sorted.map( | |
(item) => `${item.loadBalancer.albArn}: ${ | |
item.rules.Rules?.length || 'unknown rules length' | |
} | |
`, | |
)}`) | |
pulumi.log.info( | |
`Using load balancer: ${sorted[0]?.loadBalancer.albArn}`, | |
) | |
return { | |
id: cuid(), | |
outs: { | |
loadBalancerToUse: sorted[0]?.loadBalancer, | |
}, | |
} | |
}, | |
} | |
interface LeastUsedLoadBalancerArgs { | |
awsRegion: pulumi.Input<string> | |
assumeRole?: pulumi.Input<string> | |
loadBalancerArnsToCheck: pulumi.Input<SharedLoadBalancer[]> | |
} | |
export class LeastUsedLoadBalancer extends pulumi.dynamic.Resource { | |
public readonly loadBalancerToUse!: pulumi.Output<SharedLoadBalancer> | |
constructor( | |
name: string, | |
props: LeastUsedLoadBalancerArgs, | |
opts?: pulumi.CustomResourceOptions, | |
) { | |
super( | |
leastUsedLoadBalancerProvider, | |
name, | |
{ loadBalancerToUse: undefined, ...props }, | |
opts, | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment