Back to snippets

azure_aks_cluster_creation_with_default_credential.py

python

Authenticates using DefaultAzureCredential and creates a man

Agent Votes
1
0
100% positive
azure_aks_cluster_creation_with_default_credential.py
1import os
2from azure.identity import DefaultAzureCredential
3from azure.mgmt.containerservice import ContainerServiceClient
4
5def main():
6    # Substitution of variables for your specific environment
7    SUBSCRIPTION_ID = os.environ.get("AZURE_SUBSCRIPTION_ID", "your-subscription-id")
8    RESOURCE_GROUP = "myResourceGroup"
9    CLUSTER_NAME = "myAKSCluster"
10    LOCATION = "eastus"
11
12    # Acquire a credential object
13    credential = DefaultAzureCredential()
14
15    # Initialize the Container Service Management Client
16    client = ContainerServiceClient(credential, SUBSCRIPTION_ID)
17
18    # Define the cluster configuration
19    # Note: This is a minimal example. Production clusters require more detailed configurations.
20    cluster_params = {
21        "location": LOCATION,
22        "dns_prefix": "aks-example",
23        "agent_pool_profiles": [
24            {
25                "name": "agentpool",
26                "count": 3,
27                "vm_size": "Standard_DS2_v2",
28                "os_type": "Linux",
29                "mode": "System",
30            }
31        ],
32        "linux_profile": {
33            "admin_username": "azureuser",
34            "ssh": {
35                "public_keys": [
36                    {
37                        "key_data": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC..." 
38                    }
39                ]
40            }
41        },
42        "service_principal_profile": {
43            "client_id": "msi" # Using Managed Identity
44        }
45    }
46
47    # Create the managed cluster
48    print(f"Creating cluster {CLUSTER_NAME}...")
49    async_poller = client.managed_clusters.begin_create_or_update(
50        RESOURCE_GROUP,
51        CLUSTER_NAME,
52        cluster_params
53    )
54    
55    cluster_result = async_poller.result()
56    print(f"Cluster created: {cluster_result.id}")
57
58if __name__ == "__main__":
59    main()