question

BerndW-1204 avatar image
0 Votes"
BerndW-1204 asked srbose-msft commented

Create AKS cluster with python sdk

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

srbose-msft avatar image
0 Votes"
srbose-msft answered

@BerndW-1204 , 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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

BerndW-1204 avatar image
0 Votes"
BerndW-1204 answered srbose-msft commented

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

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

To create the service principal resource programmatically, yes an application object can be used. There are three types of service principal:

  • Application - The type of service principal is the local representation, or application instance, of a global application object in a single tenant or directory. In this case, a service principal is a concrete instance created from the application object and inherits certain properties from that application object. A service principal is created in each tenant where the application is used and references the globally unique app object. The service principal object defines what the app can actually do in the specific tenant, who can access the app, and what resources the app can access.
    When an application is given permission to access resources in a tenant (upon registration or consent), a service principal object is created. When you register an application using the Azure portal, a service principal is created automatically. You can also create service principal objects in a tenant using Azure PowerShell, Azure CLI, Microsoft Graph, and other tools.

[contd; Reference in next section as well]

0 Votes 0 ·
  • Managed identity - This type of service principal is used to represent a managed identity. Managed identities eliminate the need for developers to manage credentials. Managed identities provide an identity for applications to use when connecting to resources that support Azure AD authentication. When a managed identity is enabled, a service principal representing that managed identity is created in your tenant. Service principals representing managed identities can be granted access and permissions, but cannot be updated or modified directly.

  • Legacy - This type of service principal represents a legacy app, which is an app created before app registrations were introduced or an app created through legacy experiences. A legacy service principal can have credentials, service principal names, reply URLs, and other properties that an authorized user can edit, but does not have an associated app registration. The service principal can only be used in the tenant where it was created.

The Microsoft Graph ServicePrincipal entity defines the schema for a service principal object's properties.

For more information please check this document.

0 Votes 0 ·
BerndW-1204 avatar image
0 Votes"
BerndW-1204 answered

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()
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

BerndW-1204 avatar image
0 Votes"
BerndW-1204 answered

My fault. Got it

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

BerndW-1204 avatar image
0 Votes"
BerndW-1204 answered srbose-msft commented

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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@BerndW-1204 ,

I could not find an example really on the internet. But here's the next best thing: after the step creating the service principal you can update the key/password credentials respectively using:

0 Votes 0 ·