├── .funcignore ├── .gitignore ├── .vscode-defaults ├── extensions.json ├── settings.json ├── tasks.json └── launch.json ├── host.json ├── tsconfig.json ├── private-aks-dns-zone-linker ├── function.json └── index.ts ├── package.json ├── local.settings.json-default ├── LICENSE.md └── README.md /.funcignore: -------------------------------------------------------------------------------- 1 | *.js.map 2 | *.ts 3 | .git* 4 | .vscode 5 | local.settings.json 6 | tsconfig.json 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | .vscode/ 4 | .DS_Store 5 | .nvmrc 6 | package-lock.json 7 | local.settings.json 8 | -------------------------------------------------------------------------------- /.vscode-defaults/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-azurefunctions" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "extensionBundle": { 4 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 5 | "version": "[1.*, 2.0.0)" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "sourceMap": true, 6 | "outDir": "./dist" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /private-aks-dns-zone-linker/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "bindings": [ 3 | { 4 | "type": "eventGridTrigger", 5 | "direction": "in", 6 | "name": "event" 7 | } 8 | ], 9 | "scriptFile": "../dist/index.js", 10 | "entryPoint": "run" 11 | } 12 | -------------------------------------------------------------------------------- /.vscode-defaults/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.postDeployTask": "npm install", 4 | "azureFunctions.projectLanguage": "TypeScript", 5 | "azureFunctions.projectRuntime": "~3", 6 | "debug.internalConsoleOptions": "neverOpen", 7 | "azureFunctions.preDeployTask": "npm prune" 8 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "private-aks-dns-zone-linker-function", 3 | "version": "0.1.0", 4 | "license": "MIT", 5 | "main": "src/main.ts", 6 | "module": "src/main.ts", 7 | "dependencies": { 8 | "@azure/arm-privatedns": "^1.0.0", 9 | "@azure/ms-rest-nodeauth": "^3.0.3", 10 | "@azure/functions": "^1.2.0", 11 | "atob": "^2.1.2" 12 | }, 13 | "devDependencies": { 14 | "typescript": "^3.7.2", 15 | "nodemon": "^1.19.4" 16 | }, 17 | "scripts": { 18 | "build": "tsc" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /local.settings.json-default: -------------------------------------------------------------------------------- 1 | { 2 | "IsEncrypted": false, 3 | "Values": { 4 | "AzureWebJobsStorage": "", 5 | "FUNCTIONS_WORKER_RUNTIME": "node", 6 | "FUNCTIONS_EXTENSION_VERSION": "~3", 7 | "WEBSITE_RUN_FROM_PACKAGE": "", 8 | "APPINSIGHTS_INSTRUMENTATIONKEY": "", 9 | "APPLICATIONINSIGHTS_CONNECTION_STRING": "", 10 | "PRIVATE_AKS_DNS_ZONE_LINKER_AUTHENTICATION_TYPE": "", 11 | "PRIVATE_AKS_DNS_ZONE_LINKER_SP_TENANT_ID": "", 12 | "PRIVATE_AKS_DNS_ZONE_LINKER_SP_CLIENT_ID": "", 13 | "PRIVATE_AKS_DNS_ZONE_LINKER_SP_SECRET": "", 14 | "PRIVATE_AKS_DNS_ZONE_LINKER_TARGET_VNETS": "" 15 | }, 16 | "ConnectionStrings": {} 17 | } -------------------------------------------------------------------------------- /.vscode-defaults/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "command": "host start", 7 | "problemMatcher": "$func-watch", 8 | "isBackground": true, 9 | "dependsOn": "npm build" 10 | }, 11 | { 12 | "type": "shell", 13 | "label": "npm build", 14 | "command": "npm run build", 15 | "dependsOn": "npm install", 16 | "problemMatcher": "$tsc" 17 | }, 18 | { 19 | "type": "shell", 20 | "label": "npm install", 21 | "command": "npm install" 22 | }, 23 | { 24 | "type": "shell", 25 | "label": "npm prune", 26 | "command": "npm prune --production", 27 | "dependsOn": "npm build", 28 | "problemMatcher": [] 29 | }, 30 | ] 31 | } -------------------------------------------------------------------------------- /.vscode-defaults/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Launch Program", 11 | "skipFiles": [ 12 | "/**" 13 | ], 14 | "program": "${workspaceFolder}/src/main.ts", 15 | "preLaunchTask": "tsc: build - tsconfig.json", 16 | "outFiles": [ 17 | "${workspaceFolder}/dist/**/*.js" 18 | ] 19 | }, 20 | { 21 | "name": "Attach to Node Functions", 22 | "type": "node", 23 | "request": "attach", 24 | "port": 9229, 25 | "preLaunchTask": "func: host start" 26 | } 27 | ] 28 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Rasmus H. Hummelmose 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # private-aks-dns-zone-linker-function-app 2 | 3 | This function was built to allow enterprises with hub/spoke networking topologies in Azure, using their own DNS to enable name resolution to/from on-premises to use private link enabled AKS clusters as per the documentation (https://docs.microsoft.com/en-us/azure/aks/private-clusters#hub-and-spoke-with-custom-dns). 4 | 5 | ## Does this apply to you checklist 6 | 7 | - Do you have a hub/spoke networking topology in Azure? 8 | - Do you provision your own DNS server in hub networks to allow connectivity to/from on-premises? 9 | - Do you need private link enabled clusters provisioned without manual intervention? 10 | 11 | If you can answer *yes* to the above, and BYO DNS still isn't available for AKS private clusters, then it does. 12 | 13 | ## What does the function do 14 | 15 | 1. It triggers when new resources are created, reacting only to private DNS zones created by AKS 16 | 1. Gets a list of target VNets from the environment, for which a link from the private DNS zone should be created 17 | 1. Creates said links 18 | 19 | ## Instructions 20 | 21 | 1. Create a new function app with runtime stack *node* version *12* 22 | 1. Enable system managed identity on the function app 23 | 1. Grant *Network Contributor* and *DNS Contributor* roles to the function app's identity 24 | 1. On the function app, add a new application configuration variable: *PRIVATE_AKS_DNS_ZONE_LINKER_AUTHENTICATION_TYPE* with value *APP_SERVICE_MSI* 25 | 1. base64 encode a JSON array of your hub vnet resource ids. Ie. *echo -n '["id1", "id2"]' | base64* 26 | 1. On the function app, add a new application configuration variable: *PRIVATE_AKS_DNS_ZONE_LINKER_TARGET_VNETS* with a value derived from the previous bullet. 27 | 1. Run command *tsc* to compile the function app - requires TypeScript (https://www.typescriptlang.org/#download-links) 28 | 1. Run command *func azure functionapp publish * to publish the function - requires azure-functions-core-tools (https://github.com/Azure/azure-functions-core-tools) 29 | 1. Subscribe the function to all events on the subscriptions relevant 30 | 31 | ## IMPORTANT 32 | 33 | Even though the function only reacts to events of type *ResourceWriteSuccess* on the private DNS zone resource type, I've found that when applying any filters at all a significant delay is sometimes introduced from action to event, causing the function not to run in time. Sometimes the delay has been hours. 34 | 35 | I haven't been able to break it when subscribing to *ALL* events on a given subscription. 36 | -------------------------------------------------------------------------------- /private-aks-dns-zone-linker/index.ts: -------------------------------------------------------------------------------- 1 | import { AzureFunction, Context } from "@azure/functions" 2 | import { PrivateDnsManagementClient, PrivateDnsManagementModels } from "@azure/arm-privatedns"; 3 | import * as MSRest from "@azure/ms-rest-js"; 4 | import * as MSRestNodeAuth from "@azure/ms-rest-nodeauth"; 5 | import * as Util from "util"; 6 | import * as Atob from "atob"; 7 | 8 | enum EnvVars { 9 | authenticationType = "PRIVATE_AKS_DNS_ZONE_LINKER_AUTHENTICATION_TYPE", 10 | msiEndpoint = "MSI_ENDPOINT", 11 | servicePrincipalTenantId = "PRIVATE_AKS_DNS_ZONE_LINKER_SP_TENANT_ID", 12 | servicePrincipalClientId = "PRIVATE_AKS_DNS_ZONE_LINKER_SP_CLIENT_ID", 13 | servicePrincipalSecret = "PRIVATE_AKS_DNS_ZONE_LINKER_SP_SECRET", 14 | targetVNets = "PRIVATE_AKS_DNS_ZONE_LINKER_TARGET_VNETS" 15 | } 16 | 17 | enum AuthenticationType { 18 | servicePrincipalSecret = "SERVICE_PRINCIPAL_SECRET", 19 | appServiceMSI = "APP_SERVICE_MSI" 20 | } 21 | 22 | interface ResourceIdProps { 23 | id: string 24 | subscriptionId: string 25 | resourceGroupName: string 26 | name: string 27 | } 28 | 29 | const run: AzureFunction = async function (context: Context, event: Object): Promise { 30 | context.log(`Event grid trigger function processed an event: ${Util.inspect(event, {showHidden: false, depth: null})}`); 31 | const eventIdentifier = "Microsoft.Resources.ResourceWriteSuccess"; 32 | const operationNameIdentifier = "Microsoft.Network/privateDnsZones/write"; 33 | const aksIdentifier = "azmk8s.io" 34 | const resourceId: string = event["subject"]; 35 | const shouldCreateLink = event["eventType"] === eventIdentifier && event["data"]["operationName"] === operationNameIdentifier && resourceId.endsWith(aksIdentifier); 36 | if (!shouldCreateLink) { 37 | context.log(`Bailing. Link shouldn't be created for resourceId: ${resourceId}`) 38 | return; 39 | } 40 | context.log("Proceeding to process event.."); 41 | const credentials = await authenticate(context); 42 | const zoneResourceIdProps = decodePrivateDNSZoneResourceId(resourceId); 43 | const privateDNSClient = new PrivateDnsManagementClient(credentials, zoneResourceIdProps.subscriptionId); 44 | const targetVNetResourceIdsProps = targetVNetsFromEnvironment(); 45 | const zoneName = zoneResourceIdProps.name; 46 | for (const targetVNetResourceIdProps of targetVNetResourceIdsProps) { 47 | const resourceGroupName = zoneResourceIdProps.resourceGroupName; 48 | const linkName = targetVNetResourceIdProps.name; 49 | const parameters: PrivateDnsManagementModels.VirtualNetworkLink = { 50 | virtualNetwork: { 51 | id: targetVNetResourceIdProps.id 52 | }, 53 | location: "global", 54 | registrationEnabled: false 55 | } 56 | const VirtualNetworkLink = await privateDNSClient.virtualNetworkLinks.beginCreateOrUpdate(resourceGroupName, zoneName, linkName, parameters); 57 | context.log(`Created virtual network link: ${Util.inspect(VirtualNetworkLink, {showHidden: false, depth: null})}`); 58 | } 59 | }; 60 | 61 | async function authenticate(context: Context): Promise { 62 | const authenticationType = process.env[EnvVars.authenticationType]; 63 | switch (authenticationType) { 64 | case AuthenticationType.servicePrincipalSecret: { 65 | const tenantId = process.env[EnvVars.servicePrincipalTenantId]; 66 | const clientId = process.env[EnvVars.servicePrincipalClientId]; 67 | const secret = process.env[EnvVars.servicePrincipalSecret]; 68 | const credentials = await MSRestNodeAuth.loginWithServicePrincipalSecret(clientId, secret, tenantId); 69 | const castedCredentials = credentials as unknown as MSRest.ServiceClientCredentials; 70 | return castedCredentials; 71 | } 72 | case AuthenticationType.appServiceMSI: { 73 | const credentials = await MSRestNodeAuth.loginWithAppServiceMSI() 74 | const castedCredentials = credentials as unknown as MSRest.ServiceClientCredentials; 75 | return castedCredentials; 76 | } 77 | default: { 78 | throw `Unknown authentication type provided in env var ${EnvVars.authenticationType}: ${authenticationType}` 79 | } 80 | } 81 | } 82 | 83 | function targetVNetsFromEnvironment(): ResourceIdProps[] { 84 | const envVar = process.env[EnvVars.targetVNets]; 85 | if (envVar == null) { 86 | throw `No target vnets defined. They have to be set in env var ${EnvVars.targetVNets} as a base64 encoded JSON array of resource id strings.`; 87 | } 88 | const decodedEnvVar = Atob(envVar); 89 | const targetVNetResourceIds: string[] = JSON.parse(decodedEnvVar); 90 | const targetVNetResourceIdProps: ResourceIdProps[] = targetVNetResourceIds.map(decodeVNetResourceId); 91 | return targetVNetResourceIdProps; 92 | } 93 | 94 | function decodePrivateDNSZoneResourceId(resourceId: string): ResourceIdProps { 95 | return decodeCommonResourceId(resourceId); 96 | } 97 | 98 | function decodeVNetResourceId(resourceId: string): ResourceIdProps { 99 | return decodeCommonResourceId(resourceId); 100 | } 101 | 102 | function decodeCommonResourceId(resourceId: string): ResourceIdProps { 103 | const decodeRegEx = new RegExp("\/.*\/([^/]*)\/.*\/([^/]*)\/.*\/.*\/.*\/([^/]*)"); 104 | const decodeResult = decodeRegEx.exec(resourceId); 105 | let decodedResourceId: ResourceIdProps = { 106 | id: resourceId, 107 | subscriptionId: decodeResult[1], 108 | resourceGroupName: decodeResult[2], 109 | name: decodeResult[3] 110 | }; 111 | return decodedResourceId; 112 | } 113 | 114 | export = run; 115 | --------------------------------------------------------------------------------