|
| 1 | +import { NetworkManagementClient, PublicIPPrefix } from '@azure/arm-network' |
| 2 | +import { PagedAsyncIterableIterator } from '@azure/core-paging' |
| 3 | +import CloudGraph from '@cloudgraph/sdk' |
| 4 | + |
| 5 | +import azureLoggerText from '../../properties/logger' |
| 6 | +import { AzureServiceInput, TagMap } from '../../types' |
| 7 | +import { tryCatchWrapper } from '../../utils' |
| 8 | +import { lowerCaseLocation } from '../../utils/format' |
| 9 | +import { getResourceGroupFromEntity } from '../../utils/idParserUtils' |
| 10 | + |
| 11 | +const { logger } = CloudGraph |
| 12 | +const lt = { ...azureLoggerText } |
| 13 | +const serviceName = 'PublicIp' |
| 14 | + |
| 15 | +export interface RawAzurePublicIpPrefix |
| 16 | + extends Omit<PublicIPPrefix, 'tags' | 'location'> { |
| 17 | + region: string |
| 18 | + resourceGroupId: string |
| 19 | + Tags: TagMap |
| 20 | +} |
| 21 | + |
| 22 | +export default async ({ |
| 23 | + regions, |
| 24 | + config, |
| 25 | +}: AzureServiceInput): Promise<{ |
| 26 | + [property: string]: RawAzurePublicIpPrefix[] |
| 27 | +}> => { |
| 28 | + try { |
| 29 | + const { tokenCredentials, subscriptionId } = config |
| 30 | + const client = new NetworkManagementClient(tokenCredentials, subscriptionId) |
| 31 | + |
| 32 | + const publicIpPrefixData: PublicIPPrefix[] = [] |
| 33 | + await tryCatchWrapper( |
| 34 | + async () => { |
| 35 | + const publicIpPrefixIterable: PagedAsyncIterableIterator<PublicIPPrefix> = |
| 36 | + client.publicIPPrefixes.listAll() |
| 37 | + for await (const publicIpPrefix of publicIpPrefixIterable) { |
| 38 | + publicIpPrefix && publicIpPrefixData.push(publicIpPrefix) |
| 39 | + } |
| 40 | + }, |
| 41 | + { |
| 42 | + service: serviceName, |
| 43 | + client, |
| 44 | + scope: 'publicIPPrefixes', |
| 45 | + operation: 'listAll', |
| 46 | + } |
| 47 | + ) |
| 48 | + |
| 49 | + const result: { |
| 50 | + [property: string]: RawAzurePublicIpPrefix[] |
| 51 | + } = {} |
| 52 | + let numOfGroups = 0 |
| 53 | + publicIpPrefixData.forEach(({ tags, location, ...rest }) => { |
| 54 | + const region = lowerCaseLocation(location) |
| 55 | + if (regions.includes(region)) { |
| 56 | + if (!result[region]) { |
| 57 | + result[region] = [] |
| 58 | + } |
| 59 | + const resourceGroupId = getResourceGroupFromEntity(rest) |
| 60 | + result[region].push({ |
| 61 | + ...rest, |
| 62 | + region, |
| 63 | + resourceGroupId, |
| 64 | + Tags: tags || {}, |
| 65 | + }) |
| 66 | + numOfGroups += 1 |
| 67 | + } |
| 68 | + }) |
| 69 | + logger.debug(lt.foundPublicIpPrefixes(numOfGroups)) |
| 70 | + |
| 71 | + return result |
| 72 | + } catch (e) { |
| 73 | + logger.error(e) |
| 74 | + return {} |
| 75 | + } |
| 76 | +} |
0 commit comments