0
# Tenant Operations
1
2
Tenant discovery and management operations that allow applications to identify and work with Azure Active Directory tenants accessible to the authenticated user. These operations are essential for multi-tenant applications and understanding the scope of accessible resources.
3
4
## Capabilities
5
6
### List Accessible Tenants
7
8
Gets all Azure Active Directory tenants that are accessible to the authenticated user. This is useful for understanding which tenants contain subscriptions that can be managed.
9
10
```python { .api }
11
def list(**kwargs) -> Iterable[TenantIdDescription]:
12
"""
13
Gets the tenants for your account.
14
15
Returns:
16
Iterable[TenantIdDescription]: Paginated list of accessible tenants
17
"""
18
```
19
20
**Usage Example:**
21
22
```python
23
from azure.identity import DefaultAzureCredential
24
from azure.mgmt.subscription import SubscriptionClient
25
26
credential = DefaultAzureCredential()
27
client = SubscriptionClient(credential)
28
29
# List all accessible tenants
30
tenants = list(client.tenants.list())
31
print(f"Found {len(tenants)} accessible tenants:")
32
33
for tenant in tenants:
34
print(f"Tenant ID: {tenant.tenant_id}")
35
print(f"Display Name: {tenant.display_name}")
36
print(f"Default Domain: {tenant.default_domain}")
37
print(f"Category: {tenant.tenant_category}")
38
print("---")
39
```
40
41
**Advanced Usage - Working with Multiple Tenants:**
42
43
```python
44
# Get tenants and then work with subscriptions in each
45
tenants = list(client.tenants.list())
46
47
for tenant in tenants:
48
print(f"Working with tenant: {tenant.display_name}")
49
50
# Create a new client for this specific tenant if needed
51
# (Note: The credential must have access to this tenant)
52
tenant_client = SubscriptionClient(credential)
53
54
# List subscriptions accessible in this context
55
subscriptions = list(tenant_client.subscriptions.list())
56
print(f" Found {len(subscriptions)} subscriptions in this tenant")
57
58
for sub in subscriptions:
59
if sub.tenant_id == tenant.tenant_id:
60
print(f" - {sub.display_name} ({sub.subscription_id})")
61
```
62
63
## Error Handling
64
65
Common scenarios when working with tenant operations:
66
67
```python
68
from azure.core.exceptions import HttpResponseError
69
70
try:
71
tenants = list(client.tenants.list())
72
if not tenants:
73
print("No accessible tenants found - check authentication and permissions")
74
except HttpResponseError as e:
75
if e.status_code == 401:
76
print("Authentication failed - check credentials")
77
elif e.status_code == 403:
78
print("Access denied - insufficient permissions")
79
else:
80
print(f"Error listing tenants: {e.status_code} - {e.message}")
81
```
82
83
## Types
84
85
```python { .api }
86
class TenantIdDescription:
87
"""Azure Active Directory tenant information."""
88
id: str # Resource ID for the tenant
89
tenant_id: str # Azure AD tenant identifier (GUID)
90
tenant_category: str # Tenant category (Home, ProjectedBy, ManagedBy)
91
display_name: str # Human-readable tenant name
92
default_domain: str # Primary domain name for the tenant
93
country: str # Country/region where tenant is located
94
country_code: str # ISO country code
95
domains: List[str] # All verified domains in the tenant
96
tenant_type: str # Type of tenant
97
```
98
99
## Multi-Tenant Considerations
100
101
When working with multiple tenants, consider the following patterns:
102
103
### Filtering by Tenant Category
104
105
```python
106
# Get only "home" tenants (where the user is a native member)
107
home_tenants = [t for t in client.tenants.list() if t.tenant_category == "Home"]
108
109
# Get guest tenants (where the user is a guest)
110
guest_tenants = [t for t in client.tenants.list() if t.tenant_category in ["ProjectedBy", "ManagedBy"]]
111
```
112
113
### Domain-Based Tenant Identification
114
115
```python
116
def find_tenant_by_domain(domain_name: str) -> TenantIdDescription:
117
"""Find a tenant by one of its verified domains."""
118
for tenant in client.tenants.list():
119
if domain_name in tenant.domains or tenant.default_domain == domain_name:
120
return tenant
121
return None
122
123
# Example usage
124
tenant = find_tenant_by_domain("contoso.com")
125
if tenant:
126
print(f"Found tenant: {tenant.display_name} ({tenant.tenant_id})")
127
```
128
129
### Tenant Permissions Check
130
131
```python
132
def check_tenant_access(tenant_id: str) -> bool:
133
"""Check if we have access to a specific tenant."""
134
try:
135
accessible_tenants = list(client.tenants.list())
136
return any(t.tenant_id == tenant_id for t in accessible_tenants)
137
except HttpResponseError:
138
return False
139
```
140
141
## Integration with Subscription Operations
142
143
Tenant operations are commonly used in conjunction with subscription operations:
144
145
```python
146
# Get all tenants and their associated subscriptions
147
for tenant in client.tenants.list():
148
print(f"Tenant: {tenant.display_name}")
149
150
# Get all subscriptions
151
all_subscriptions = list(client.subscriptions.list())
152
153
# Filter subscriptions for this tenant
154
tenant_subscriptions = [s for s in all_subscriptions if s.tenant_id == tenant.tenant_id]
155
156
print(f" Subscriptions in this tenant: {len(tenant_subscriptions)}")
157
for sub in tenant_subscriptions:
158
print(f" - {sub.display_name} ({sub.state})")
159
```