Create AKS cluster with python sdk

Bernd W 1 Reputation point
2021-08-23T14:05:39.89+00:00

Hi I would like to create an aks cluster with the python sdk as in

az aks create --resource-group ${K8S_RESOURCE_GROUP} \
--name ${K8S_CLUSTER_NAME} \
--kubernetes-version 1.19.9 \
--enable-cluster-autoscaler \
--min-count 10 \
--max-count 35 \
--node-count 10 \
--node-vm-size Standard_E2ds_v4 \
--enable-addons monitoring,http_application_routing \
--generate-ssh-keys

It seems that I need to create a service principal with the graphrbac package first. But I don't get it working. For a service principal I need an app id, which I don't have.
Is there an example I can use.

Regards

Bernd

Azure Kubernetes Service (AKS)
Azure Kubernetes Service (AKS)
An Azure service that provides serverless Kubernetes, an integrated continuous integration and continuous delivery experience, and enterprise-grade security and governance.
2,140 questions
0 comments No comments
{count} votes

5 answers

Sort by: Most helpful
  1. SRIJIT-BOSE-MSFT 4,336 Reputation points Microsoft Employee
    2021-08-23T14:59:37.143+00:00

    @Bernd W , thank you for your question.

    You can create an Azure Service Principal in the Azure CLI using the az ad sp create-for-rbac command. How-to guide

    To create Service principal using the Azure Python SDK graphrbac package, here is an example. In this case the app object is created here.

    Reference: https://stackoverflow.com/a/47958873/16169604

    ----------

    Hope this helps.

    Please "Accept as Answer" if it helped, so that it can help others in the community looking for help on similar topics.

    0 comments No comments

  2. Bernd W 1 Reputation point
    2021-08-23T15:35:10.357+00:00

    So this means that I have to create an app object for the future aks cluster first?


  3. Bernd W 1 Reputation point
    2021-08-24T08:18:26.683+00:00

    Many thanks for your help. Now I'm stuck with the creation of the aks cluster. Stupidly the error message is not very helpful.

    containerservice_client.managed_clusters.begin_create_or_update(RESOURCE_GROUP_NAME, K8S_CLUSTER_NAME, parameters)
    

    File "/usr/local/lib/python3.9/site-packages/azure/mgmt/containerservice/v2021_07_01/operations/_managed_clusters_operations.py", line 736, in begin_create_or_update
    raw_result = self._create_or_update_initial(
    File "/usr/local/lib/python3.9/site-packages/azure/mgmt/containerservice/v2021_07_01/operations/_managed_clusters_operations.py", line 678, in _create_or_update_initial
    body_content = self._serialize.body(parameters, 'ManagedCluster')
    File "/usr/local/lib/python3.9/site-packages/msrest/serialization.py", line 626, in body
    errors = _recursive_validate(data_type, data_type, data)
    File "/usr/local/lib/python3.9/site-packages/msrest/serialization.py", line 160, in _recursive_validate
    return data.validate()
    File "/usr/local/lib/python3.9/site-packages/msrest/serialization.py", line 254, in validate
    validation_result += _recursive_validate(attr_name, attr_type, value)
    File "/usr/local/lib/python3.9/site-packages/msrest/serialization.py", line 152, in _recursive_validate
    for content in data:
    TypeError: 'ManagedClusterAgentPoolProfile' object is not iterable

    Process finished with exit code 1

    # Obtain the management object for resources.
    resource_client = ResourceManagementClient(credential, SUBSCRIPTION_ID)
    
    # Provision the resource group
    rg_result = resource_client.resource_groups.create_or_update(
        RESOURCE_GROUP_NAME,
        {
            "location": LOCATION,
            "tags": {"environment": "test", "department": "tech"}
        })
    logging.getLogger("main").info(f"Provisioned resource group {rg_result.name} in the {rg_result.location} region")
    
    for app in get_client_from_cli_profile(GraphRbacManagementClient).applications.list(filter="displayName eq 'RTTS ICE AKS Cluster'"):
        get_client_from_cli_profile(GraphRbacManagementClient).applications.delete(app.object_id)
    
    app = get_client_from_cli_profile(GraphRbacManagementClient).applications.create({
        'available_to_other_tenants': False,
        'display_name': 'RTTS ICE AKS Cluster',
        'identifier_uris': ['http://test123.org/']
    })
    logging.getLogger("main").info(f"Provisioned application app.display_name with id {app.app_id}")
    
    
    # create aks cluster service principal. Use get_client_from_cli_profile for legacy library here
    sp_params = azure.graphrbac.models.ServicePrincipalCreateParameters(app_id=app.app_id, app_role_assignment_required=False, account_enabled=True)
    sp_result = get_client_from_cli_profile(GraphRbacManagementClient).service_principals.create(sp_params)
    logging.getLogger("main").info(f"Provisioned service principal {sp_result.object_id}")
    
    
    containerservice_client = ContainerServiceClient(credential, SUBSCRIPTION_ID)
    parameters = ManagedCluster(
        location=LOCATION,
        kubernetes_version="1.19.1",
        enable_rbac=True,
        service_principal_profile=ManagedClusterServicePrincipalProfile(client_id=sp_result.object_id),
        agent_pool_profiles=ManagedClusterAgentPoolProfile(name=K8S_CLUSTER_NAME,
                                                           vm_size='Standard_E2ds_v4',
                                                           count=1,
                                                           min_count=1,
                                                           max_count=30,
                                                           enable_auto_scaling=True)
    )
    containerservice_client.managed_clusters.begin_create_or_update(RESOURCE_GROUP_NAME, K8S_CLUSTER_NAME, parameters)
    
    # Optional lines to delete the resource group. begin_delete is asynchronous.
    poller = resource_client.resource_groups.begin_delete(rg_result.name)
    result = poller.result()
    
    0 comments No comments

  4. Bernd W 1 Reputation point
    2021-08-24T09:33:07.237+00:00

    My fault. Got it

    0 comments No comments

  5. Bernd W 1 Reputation point
    2021-08-25T06:09:22.033+00:00

    Is there maybe an example for creating a service principal with credentials (key or password)? When creating the cluster the service_principal_profile needs a secret.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.