Skip to content

Commit 97f98c7

Browse files
2208911 Create PR for the Azure-arm-rest Common lib and update related task (#395)
* 2208911 Create PR for the Azure-arm-rest Common lib and update related task * Fixed Test case issue
1 parent a366b66 commit 97f98c7

12 files changed

+165
-8
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export declare function AksServiceTests(): void;
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import assert = require("assert");
2+
import * as ttm from 'azure-pipelines-task-lib/mock-test';
3+
import tl = require('azure-pipelines-task-lib');
4+
import * as path from 'path';
5+
6+
export function AksServiceTests() {
7+
it('azure-arm-aks-service AksService', (done: Mocha.Done) => {
8+
let tp = path.join(__dirname, 'azure-arm-aks-service-tests.js');
9+
let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
10+
let passed: boolean = true;
11+
12+
tr.runAsync().then(() => {
13+
assert(tr.stdOutContained("Aks Cluster Credential Found: clusterAdmin"), "Should have printed: Aks Cluster Credential Found: clusterAdmin");
14+
assert(tr.stdOutContained("Aks Cluster Credential Found: clusterUser"), "Should have printed: Aks Cluster Credential Found: clusterUser");
15+
assert(tr.stdOutContained("Aks Cluster Credential Found: customUser"), "Should have printed: Aks Cluster Credential Found: customUser");
16+
done();
17+
})
18+
.catch((error) => {
19+
passed = false;
20+
console.log(tr.stdout);
21+
console.log(tr.stderr);
22+
done(error);
23+
});
24+
});
25+
}

common-npm-packages/azure-arm-rest/Tests/L0.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { KuduServiceTests } from "./L0-azure-arm-app-service-kudu-tests";
33
import { ApplicationInsightsTests } from "./L0-azure-arm-appinsights-tests";
44
import { ApplicationInsightsTests as ApplicationInsightsTestsWebTests } from "./L0-azure-arm-appinsights-webtests-tests";
55
import { ResourcesTests } from "./L0-azure-arm-resource-tests";
6+
import { AksServiceTests } from "./L0-azure-arm-aks-service-tests";
67
const DEFAULT_TIMEOUT = 1000 * 20;
78

89
describe("AzureARMRestTests", function () {
@@ -12,4 +13,5 @@ describe("AzureARMRestTests", function () {
1213
describe("ApplicationInsightsTests", ApplicationInsightsTests.bind(ApplicationInsightsTests, DEFAULT_TIMEOUT))
1314
describe("ApplicationInsightsWeb tests", ApplicationInsightsTestsWebTests.bind(ApplicationInsightsTestsWebTests, DEFAULT_TIMEOUT))
1415
describe("Resources Tests", ResourcesTests.bind(ResourcesTests, DEFAULT_TIMEOUT));
16+
describe("AKS Tests", AksServiceTests.bind(AksServiceTests, DEFAULT_TIMEOUT));
1517
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export declare class AksServiceTests {
2+
static credentialsByClusterAdmin(): Promise<void>;
3+
static credentialsByClusterUser(): Promise<void>;
4+
static credentialsByCustomClusterUser(): Promise<void>;
5+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { getMockEndpoint, nock, mockAzureAksServiceTests } from './mock_utils';
2+
import tl = require('azure-pipelines-task-lib');
3+
import { AzureAksService } from '../azure-arm-aks-service';
4+
5+
var endpoint = getMockEndpoint();
6+
7+
// Mock all calls for Azure AKS Service
8+
mockAzureAksServiceTests();
9+
10+
export class AksServiceTests {
11+
public static async credentialsByClusterAdmin() {
12+
let aksService: AzureAksService = new AzureAksService(endpoint);
13+
try {
14+
let result = await aksService.getClusterCredential("MOCK_RESOURCE_GROUP_NAME", "MOCK_CLUSTER", true);
15+
console.log(`Aks Cluster Credential Found: ${result.name}`);
16+
}
17+
catch(error) {
18+
console.log(error);
19+
tl.setResult(tl.TaskResult.Failed, 'AksServiceTests.credentialsByClusterAdmin() should have passed but failed');
20+
}
21+
}
22+
23+
public static async credentialsByClusterUser() {
24+
let aksService: AzureAksService = new AzureAksService(endpoint);
25+
try {
26+
let result = await aksService.getClusterCredential("MOCK_RESOURCE_GROUP_NAME", "MOCK_CLUSTER", false);
27+
console.log(`Aks Cluster Credential Found: ${result.name}`);
28+
}
29+
catch(error) {
30+
console.log(error);
31+
tl.setResult(tl.TaskResult.Failed, 'AksServiceTests.credentialsByClusterUser() should have passed but failed');
32+
}
33+
}
34+
35+
public static async credentialsByCustomClusterUser() {
36+
let aksService: AzureAksService = new AzureAksService(endpoint);
37+
try {
38+
let result = await aksService.getClusterCredential("MOCK_RESOURCE_GROUP_NAME", "MOCK_CLUSTER", false, 'customUser');
39+
console.log(`Aks Cluster Credential Found: ${result.name}`);
40+
}
41+
catch(error) {
42+
console.log(error);
43+
tl.setResult(tl.TaskResult.Failed, 'AksServiceTests.credentialsByCustomClusterUser() should have passed but failed');
44+
}
45+
}
46+
}
47+
48+
async function RUNTESTS() {
49+
await AksServiceTests.credentialsByClusterAdmin();
50+
await AksServiceTests.credentialsByClusterUser();
51+
await AksServiceTests.credentialsByCustomClusterUser();
52+
}
53+
54+
RUNTESTS();

common-npm-packages/azure-arm-rest/Tests/mock_utils.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ export declare function mockAzureApplicationInsightsTests(): void;
66
export declare function mockAzureAppServiceTests(): void;
77
export declare function mockKuduServiceTests(): void;
88
export declare function mockAzureARMResourcesTests(): void;
9+
export declare function mockAzureAksServiceTests(): void;

common-npm-packages/azure-arm-rest/Tests/mock_utils.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,4 +718,37 @@ export function mockAzureARMResourcesTests() {
718718
properties: {}
719719
}]
720720
}).persist();
721+
}
722+
723+
export function mockAzureAksServiceTests() {
724+
nock('https://management.azure.com', {
725+
reqheaders: {
726+
"authorization": "Bearer DUMMY_ACCESS_TOKEN",
727+
"content-type": "application/json; charset=utf-8"
728+
}
729+
}).post("/subscriptions/MOCK_SUBSCRIPTION_ID/resourceGroups/MOCK_RESOURCE_GROUP_NAME/providers/Microsoft.ContainerService/managedClusters/MOCK_CLUSTER/listClusterUserCredential?api-version=2024-05-01")
730+
.reply(200, {
731+
kubeconfigs: [{
732+
name: "clusterUser",
733+
value: "base46kubeconfig"
734+
},
735+
{
736+
name: "customUser",
737+
value: "base46kubeconfig"
738+
}]
739+
}).persist();
740+
741+
nock('https://management.azure.com', {
742+
reqheaders: {
743+
"authorization": "Bearer DUMMY_ACCESS_TOKEN",
744+
"content-type": "application/json; charset=utf-8"
745+
}
746+
}).post("/subscriptions/MOCK_SUBSCRIPTION_ID/resourceGroups/MOCK_RESOURCE_GROUP_NAME/providers/Microsoft.ContainerService/managedClusters/MOCK_CLUSTER/listClusterAdminCredential?api-version=2024-05-01")
747+
.reply(200, {
748+
kubeconfigs: [{
749+
name: "clusterAdmin",
750+
value: "base46kubeconfig"
751+
}]
752+
}).persist();
753+
721754
}

common-npm-packages/azure-arm-rest/azure-arm-aks-service.ts

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ export class AzureAksService {
2828
this._client = new ServiceClient(endpoint.applicationTokenCredentials, endpoint.subscriptionID, 30);
2929
}
3030

31-
public beginRequest(uri: string, parameters: {}) : Promise<webClient.WebResponse> {
31+
public beginRequest(uri: string, parameters: {}, apiVersion: string, method: string) : Promise<webClient.WebResponse> {
3232
var webRequest = new webClient.WebRequest();
33-
webRequest.method = 'GET';
34-
webRequest.uri = this._client.getRequestUri(uri, parameters, null,'2017-08-31');
33+
webRequest.method = method || 'GET';
34+
webRequest.uri = this._client.getRequestUri(uri, parameters, null, apiVersion);
3535
return this._client.beginRequestExpBackoff(webRequest, 3).then((response)=>{
3636
if(response.statusCode >= 200 && response.statusCode < 300) {
3737
return response;
@@ -48,10 +48,36 @@ export class AzureAksService {
4848
'{ResourceGroupName}': resourceGroup,
4949
'{ClusterName}': clusterName,
5050
'{AccessProfileName}': accessProfileName
51-
}).then((response) => {
51+
}, '2017-08-31', "GET").then((response) => {
5252
return response.body;
5353
}, (reason) => {
5454
throw Error(tl.loc('CantDownloadAccessProfile',clusterName, this._client.getFormattedError(reason)));
5555
});
5656
}
57+
58+
public getClusterCredentials(resourceGroup : string , clusterName : string, useClusterAdmin?: boolean): Promise<Model.AKSCredentialResults> {
59+
var credentialAction = !!useClusterAdmin ? 'listClusterAdminCredential' : 'listClusterUserCredential';
60+
return this.beginRequest(`//subscriptions/{subscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{ClusterName}/{CredentialAction}`,
61+
{
62+
'{ResourceGroupName}': resourceGroup,
63+
'{ClusterName}': clusterName,
64+
'{CredentialAction}': credentialAction
65+
}, '2024-05-01', "POST").then((response) => {
66+
return response.body;
67+
}, (reason) => {
68+
throw Error(tl.loc('CantDownloadClusterCredentials',clusterName, this._client.getFormattedError(reason)));
69+
});
70+
}
71+
72+
public getClusterCredential(resourceGroup : string , clusterName : string, useClusterAdmin?: boolean, credentialName?: string): Promise<Model.AKSCredentialResult> {
73+
var credentialName = !!credentialName ? credentialName : !!useClusterAdmin ? 'clusterAdmin' : 'clusterUser';
74+
var clusterCredentials = this.getClusterCredentials(resourceGroup, clusterName, useClusterAdmin)
75+
return clusterCredentials.then((credentials) => {
76+
var credential = credentials.kubeconfigs.find(credential => credential.name == credentialName)
77+
if (credential === undefined) {
78+
throw Error(tl.loc('CantDownloadClusterCredentials', clusterName, `${credentialName} not found in the list of cluster credentials.`));
79+
}
80+
return credential;
81+
})
82+
}
5783
}

common-npm-packages/azure-arm-rest/azureModels.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,15 @@ export interface AKSClusterAccessProfile extends AzureBaseObject {
305305
properties: AKSClusterAccessProfileProperties
306306
}
307307

308+
export interface AKSCredentialResult {
309+
name: string;
310+
value: string;
311+
}
312+
313+
export interface AKSCredentialResults extends AzureBaseObject {
314+
kubeconfigs: Array<AKSCredentialResult>
315+
}
316+
308317
export interface IThresholdRuleConditionDataSource {
309318
"odata.type": string;
310319
resourceUri: string;

common-npm-packages/azure-arm-rest/module.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@
185185
"UpdatedAppServiceConfigurationSettings": "Updated App Service Configuration settings.",
186186
"UpdatingAppServiceApplicationSettings": "Updating App Service Application settings. Data: %s",
187187
"UpdatingAppServiceConfigurationSettings": "Trying to update App Service Configuration settings. Data: %s",
188-
"VirtualApplicationDoesNotExist": "Virtual application doesn't exists : %s"
188+
"VirtualApplicationDoesNotExist": "Virtual application doesn't exists : %s",
189+
"CantDownloadClusterCredentials": "Cannot fetch the credentials for the cluster %s. Reason %s."
189190
}
190191
}

0 commit comments

Comments
 (0)