delucaezequiel
delucaezequiel

Reputation: 629

Deploy resource in Azure with python

I am working on deploy resources in Azure using python based on provided templates. As a starting point I am working with https://github.com/Azure-Samples/Hybrid-Resource-Manager-Python-Template-Deployment

Using as it is, I am having an issue at the beginning of the deployment (deployer.py deploy function)

def deploy(self, template, parameters):
  """Deploy the template to a resource group."""
  self.client.resource_groups.create_or_update(
  self.resourceGroup,
  {
    'location': os.environ['AZURE_RESOURCE_LOCATION']
  }
)

The error message is

Message='ServicePrincipalCredentials' object has no attribute 'get_token'

The statement is correct, ServicePrincipalCredentials get_token attribute doesn't exist, however token is, may be an error due to an outdated version?

Based on the constructor information, the error may be on credentials creation or client creation

def __init__(self, subscription_id, resource_group, pub_ssh_key_path='~/id_rsa.pub'):
  mystack_cloud = get_cloud_from_metadata_endpoint(
    os.environ['ARM_ENDPOINT'])
  subscription_id = os.environ['AZURE_SUBSCRIPTION_ID'] //This may be an error as subscription_id is already provided as a parameter
  credentials = ServicePrincipalCredentials(
    client_id=os.environ['AZURE_CLIENT_ID'],
    secret=os.environ['AZURE_CLIENT_SECRET'],
    tenant=os.environ['AZURE_TENANT_ID'],
    cloud_environment=mystack_cloud
  ) --> here   
  self.subscription_id = subscription_id
  self.resource_group = resource_group
  self.dns_label_prefix = self.name_generator.haikunate()
  pub_ssh_key_path = os.path.expanduser(pub_ssh_key_path)
  # Will raise if file not exists or not enough permission
  with open(pub_ssh_key_path, 'r') as pub_ssh_file_fd:
    self.pub_ssh_key = pub_ssh_file_fd.read()
  self.credentials = credentials
  self.client = ResourceManagementClient(self.credentials, self.subscription_id,
    base_url=mystack_cloud.endpoints.resource_manager) --> here

Do you know how I can fix this?

Upvotes: 1

Views: 91

Answers (1)

delucaezequiel
delucaezequiel

Reputation: 629

After struggling a little, I could find a solution. Just replace

credentials = ServicePrincipalCredentials(
    client_id=os.environ['AZURE_CLIENT_ID'],
    secret=os.environ['AZURE_CLIENT_SECRET'],
    tenant=os.environ['AZURE_TENANT_ID'],
    cloud_environment=mystack_cloud
  )

for

self.credentials = DefaultAzureCredential()

The final code looks like:

from azure.identity import DefaultAzureCredential
def __init__(self, subscriptionId, resourceGroup):
  endpoints = get_cloud_from_metadata_endpoint(os.environ.get("ARM_ENDPOINT"))
  self.subscriptionId = subscriptionId
  self.resourceGroup = resourceGroup
  self.credentials = DefaultAzureCredential()
  self.client = ResourceManagementClient(self.credentials, self.subscriptionId,
  base_url=endpoints.endpoints.resource_manager)

Upvotes: 1

Related Questions