Link existing B2C tenant via Azure CLI - azure

How to link an existing B2C tenant programatically via Azure CLI? Running this line:
az resource create --resource-group <rg> --resource-type Microsoft.AzureActiveDirectory/b2cDirectories --name <tenant>.onmicrosoft.com --location Europe --properties "{\"tenantId\": \"<tenantId>\", \"sku\": { \"name\": \"Standard\", \"tier\": \"A0\" } }"
Returns BadRequestError: The 'sku' property is required for creating a b2c directory resource but it is there
The ARM "B2C Link Resource" looks like this:
{
"type": "Microsoft.AzureActiveDirectory/b2cDirectories",
"apiVersion": "2017-01-30",
"name": "[parameters('name')]",
"location": "[parameters('location')]",
"tags": {},
"sku": {
"name": "Standard",
"tier": "A0"
},
"properties": {
"tenantId": "[parameters('tenantId')]"
}
}
Further Information:
I have tried different variations regarding the sku portion such as leaving it out completely or moving it as a dedicated parameter --sku Standard etc but none of them seem to work
Removing an existing link via az resource delete --ids /subscriptions/<subscriptionId>/resourceGroups/<rg>/providers/Microsoft.AzureActiveDirectory/b2cDirectories/<tenant>.onmicrosoft.com works perfectly fine
Why do we need this? We automate our infra deployment with Terraform. We're aware of the limitations automating B2C tenants (see here, here or here) so we aim for removing/adding the b2c link via pipeline to at least keep the subscription clean on destroying/applying infra.
Linking an existing B2C tenant via Azure Portal looks like this
Any advice appreciated. Thanks for your help!

I don't think Azure CLI currently can have the ability to manage B2C tenants.
As you are aware already, there is a detailed discussion done https://github.com/Azure/azure-cli/issues/12058
Other Programmatic Approach:
I had captured Fiddler Traces to understand the flow / or the endpoint that is responsible. I was able point to the below endpoint. I was checking for the create a new Azure B2C Tenant.
PUT https://management.azure.com/subscriptions/SUBSCRIBTION/resourceGroups/RESOURCEGROUP/providers/Microsoft.AzureActiveDirectory/b2cDirectories/contosoorganiztion.onmicrosoft.com?api-version=2019-01-01-preview
{"location":"United States","sku":{"name":"Standard","tier":"A0"},"properties":{"createTenantProperties":{"displayName":"Contoso Organization","countryCode":"US"}}}
However, I was not able to check the "Link to existing the Tenant" (for your requirement) option at my end due to permissions at my end. But I am assuming there should be a similar endpoint responsible for the same. You could capture Fiddler traces with Https decrypted (or any tool that will help capturing the decrypted HTTPS Traffic), trying to link an existing tenant to understand the endpoint and the request body.
Note :
Keep mind this API/endpoint is not supported and subject to change thus not recommended for production environments:
You will need access token in order to hit the endpoint.
To obtain token, resource id of the Azure portal would be :74658136-14ec-4630-ad9b-26e160ff0fc6
az account get-access-token --resource 74658136-14ec-4630-ad9b-26e160ff0fc6

Related

Some azure cli commands return SubscriptionNotExists errors?

I have a free trial subscription on Azure:
$ az account subscription list
Command group 'account subscription' is experimental and under development. Reference and support levels: https://aka.ms/CLI_refstatus
[
{
"authorizationSource": "RoleBased",
"displayName": "Azure subscription 1",
"id": "/subscriptions/fffffff-ffff-ffff-ffff-ffffffffffff",
"state": "Enabled",
"subscriptionId": "fffffff-ffff-ffff-ffff-ffffffffffff",
"subscriptionPolicies": {
"locationPlacementId": "Public_2014-09-01",
"quotaId": "FreeTrial_2014-09-01",
"spendingLimit": "On"
}
}
]
but when I execute the command (list MariaDB SKUs) I get the following error:
$ az mariadb server list-skus --location eastus
(SubscriptionNotExists) Subscription 'fffffff-ffff-ffff-ffff-ffffffffffff' does not exist.
Code: SubscriptionNotExists
Message: Subscription 'fffffff-ffff-ffff-ffff-ffffffffffff' does not exist.
Works fine under my other account where I have a pay-as-you-go subscription. Same thing with the go SDK.
If the free trial is the issue it would be great to document it somewhere.
Turns out you have to register provider resources for your subscription before you can use them. For some reason MariaDB was already registered for one of my accounts but not for the other. The error SubscriptionNotExists is extremely confusing in that regard.
To list the skus list Mariadb Please make sure that you have logged in successfully using az login cmdlet .
Then try to execute the following command which you are using
az mariadb server list-skus --location eastus
OUTPUT FOR REFERENCE:-
NOTE:- Try to close and reopen your terminal and use az login and choose your account in which you have free trail subscription then use the command.
As i don't have any free trial subscription to test it on my environment .
AFAIK, we can use it For free trail account as well based on the below screenshot and also can Check this Microsoft Document :
For more details please refer the below links for Azure free trial supported resources:
MICROSOFT DOCUMENTATION:- Azure free account FAQ ,Azure subscription and service limits, quotas, and constraints & az mariadb server list-skus

Not able to to register namespace 'Microsoft.AlertsManagement' through ARM templates

I am trying to build my infrastructure and my infrastructure through ARM templates. But getting the following error.
{
"status": "Failed",
"error": {
"code": "MissingSubscriptionRegistration",
"message": "The subscription is not registered to use namespace 'Microsoft.AlertsManagement'. See https://aka.ms/rps-not-found for how to register subscriptions.",
"details": [
{
"code": "MissingSubscriptionRegistration",
"target": "Microsoft.AlertsManagement",
"message": "The subscription is not registered to use namespace 'Microsoft.AlertsManagement'. See https://aka.ms/rps-not-found for how to register subscriptions."
}
]
}
}
When I checked further it looks like my subscription is not registered to the resource provider 'Microsoft.AlertsManagement' (See picture below)
https://i.stack.imgur.com/wTxDD.jpg
I know how I can fix this by going through the Azure portal and registering my Azure Subscription. But I am not able to do the same through ARM templates. Anyone has seen a similar issue and how can I fix it.
I believe it has something to do with the API version of
"applicationInsightsApiVersion": "2015-05-01",
I am not quite sure what could be the issue, I tried changing the version of the API but no help there.
Registering a resource provider is done at the subscription level.
Looking at the supported resources to deploy ARM template at the subscription level, it is not possibe:
Subscription deployments with ARM templates
Your best option would be to use Az CLI or Az Powershell as describe here:
Resolve errors for resource provider registration
Az Powershell:
Register-AzResourceProvider -ProviderNamespace Microsoft.AlertsManagement
Az CLI:
az provider register --namespace Microsoft.AlertsManagement

Azure VPN Gateway configuration: Get-AzureRmVirtualNetworkGatewayConnection returns ResourceNotFound error

I am trying to configure a VPN in Azure Powershell following the procedure here. When running the following command
$connection6 = Get-AzureRmVirtualNetworkGatewayConnection -Name <myconnectionname> -ResourceGroupName <myresourcegroupname>
I receive the error
Get-AzVirtualNetworkGatewayConnection: Resource group '' could not be found.
But when I run the command:
az group show --name "<myresourcegroupname>"
The return value is the object description of the resource group:
> {
> "id": "/subscriptions/<active subscription id>/resourceGroups/<myresourcegroupname>",
> "location": "<mylocation>",
> "managedBy": null,
> "name": "<myresourcegroupname>",
> "properties": {
> "provisioningState": "Succeeded" },
> "tags": null,
> "type": "Microsoft.Resources/resourceGroups"
>}
Clearly, the resource group exists and is accessible to powershell through the active subscription (and I confirmed that the active subscription does contain this resource group).
How can I properly identify the resource group for this command to run?
Thank you to the people who commented. I ended up speaking with Azure support -- the network engineer initially ran into the same problem, and tried a few different options.
Ultimately, the solution ended up being fairly simple, as the issue was the fact that multiple subscriptions were under the account. The solution was just to run
Select-azsubscription -SubscriptionID <subscriptionid>
with the proper parent subscription id. As #Joy Wang suggested, updating all the cmdlets to the newer az versions also helped clear up errors.

Network Rules of storage account blocking container creation

Following the instructions for the Azure CLI "quickstart" on creating a blob.
It looks like something in the default storage account is blocking the ability to create new containers; yet, the "defaultAction" is Allow:
The following Azure CLI:
az storage container create --account-name meaningfulname --name nancy --auth-mode login
... results in the error explaining the network rules of the Storage Account might be the cause:
The request may be blocked by network rules of storage account. Please check network rule set using 'az storage account show -n accountname --query networkRuleSet'.
If you want to change the default action to apply when no rule matches, please use 'az storage account update'.
Using the suggestion from the above message, the "show" command on the account-name gives:
> az storage account show -n meaningfulname --query networkRuleSet
{
"bypass": "AzureServices",
"defaultAction": "Allow",
"ipRules": [],
"virtualNetworkRules": []
}
I would think that the Azure CLI would be among the "services" that could bypass and do operations. And, the default action would seem to me to be quite permissive.
I've done to searching around by the error messages and commands (and variations). There does not appear to be much on what I don't know the quirks of the Azure CLI, so maybe this is so obvious that people haven't written anything up. I don't think I'm duplicating
Although the selected answer is different.
There can be another reason as in my case. You need to be in the role before you can create a container as stated by Microsoft documentation here
Before you create the container, assign the Storage Blob Data
Contributor role to yourself. Even though you are the account owner,
you need explicit permissions to perform data operations against the
storage account.
Also note that
Azure role assignments may take a few minutes to propagate.
Not sure if this would be helpful ...
If you update the "Firewalls and virtual networks" section of the Storage account and make it accessible for all networks , using CLI , it takes sometime to take effect. I have observed that it takes around 10 -30 seconds to take effect.
Try waiting for 30 seconds and then try the az container create statement. It should work.
Remove the --auth-mode login from your command. Use it like this:
az storage container create \
--account-name helloworld12345 \
--name images \
--public-access container
If we don't set --auth-mode, it uses the default auth-mode key. Which will query for the account key inside your storage account
https://learn.microsoft.com/en-us/azure/storage/blobs/authorize-data-operations-cli
Use --auth-mode login if you have required RBAC roles in your command. For more information about RBAC roles in storage, visit https://learn.microsoft.com/en-us/azure/storage/common/storage-auth-aad-rbac-cli.
The current networkRuleSet configuration is enough. I can not reproduce this issue with the same networkRuleSet configuration as you. So you may double-check if there is a typo for the storage account when creating a container or querying the networkRuleSet.
By default, storage accounts accept connections from clients on any network. To limit access to selected networks, you must first change the default action.
If you need to only allow access your storage account from some specific IP addresses or specific subnets and allow Azure services, you can add it like this,
{
"bypass": "AzureServices",
"defaultAction": "Deny",
"ipRules": [
{
"action": "Allow",
"ipAddressOrRange": "100.100.100.100"
}
],
"virtualNetworkRules": [
{
"action": "Allow",
"virtualNetworkResourceId": "subnetID"
}
]
}
With Azure CLI, Set the default rule to allow network access by default.
az storage account update --resource-group "myresourcegroup" --name "mystorageaccount" --default-action Deny
az storage account update --resource-group "myresourcegroup" --name "mystorageaccount" --default-action Allow
See Change the default network access rule for more details.
Edit
In this case, you set the --auth-mode parameter to login to authorize with Azure AD credentials. You need to ensure that the Azure AD security principal with which you sign in to Azure CLI has permission to do data operations against Blob or Queue storage. For more information about RBAC roles in Azure Storage, see Manage access rights to Azure Storage data with RBAC.

What is the command for Enabling diagnostic logs on Azure AD with PowerShell?

I am preparing an script that enables Diagnostics logs sending them to an Storage Account.
Get-AzureRmResource | foreach {
#For now adding all registered resources to Diagnostics Logs. Should narrow to specific resource types?
#Categories "Execution", "Request" only, the "AllMetrics" category intended to log all categories fail. Can add specific categories to each resource type.
Write-Output "Adding resource $_.ResourceId to the storage"
Set-AzureRmDiagnosticSetting -ResourceId $_.ResourceId -StorageAccountId $storageid -Enabled $true -RetentionEnabled $true -RetentionInDays 90 -Categories “Execution”,“Request”
}
This PowerShell command matches to enable the Diagnostics Logs to the resources created within the Subscription.
What about to enable the Diagnostigs Logs in Azure Active Directory? They include Audit and Sign-In logs?
Can someone please adivice?
Many thanks!
Sergio
Update:
I am required to automate the following with PowerShell:
1. Go to Azure Portal
2. On the left blade, select Azure Active Directory
3. Select Audit Logs or Sign-In logs 4. On the top Menu, select Export Data Settings
5.Click Add diagnostic setting
6. Check Archive to Storage Account and Set Retention days.
Process described in video:
Video discussing Azure AD reports shows how to enable the Logs, I am required to automate enabling the logs, not getting the report
MSOL offers these log / audit resources.
Collect and consume log data from your Azure resources
Azure Monitor diagnostic logs are logs emitted by an Azure service
that provide rich, frequent data about the operation of that service.
Azure Monitor makes available two types of diagnostic logs:
• Tenant logs - these logs come from tenant-level services that exist
outside of an Azure subscription, such as Azure Active Directory logs.
• Resource logs - these logs come from Azure services that deploy
resources within an Azure subscription, such as Network Security
Groups or Storage Accounts.
https://learn.microsoft.com/en-us/azure/monitoring-and-diagnostics/monitoring-overview-of-diagnostic-logs
Azure Active Directory Audit logs
Audit events currently provided from the management portal are also
downloadable per documentation at Azure Active Directory Audit Report
Events. It is now convenient for an admin of an organization to gather
critical changes that are happening in their Azure Active Directory
tenant.
https://blogs.msdn.microsoft.com/azuresecurity/2015/06/11/azure-active-directory-audit-logs
What other logs are you trying to enable beyond the above?
What are you after?
Note: AAD is not ADDS from a diagnostics approach perspective.
Update for OP
Audit Logs for Azure Events
https://blogs.msdn.microsoft.com/cloud_solution_architect/2015/03/10/audit-logs-for-azure-events/
Retrieving Resource Metrics and Creating Alert Rules via Azure
PowerShell
Metric Definitions
The Get-AzureRmMetric cmdlet downloads the definitions of an Azure
Insights metric. For example, the following retrieves the definitions
for a VM named myVM in a resource group named myRG:
$resourceId = '/subscriptions/SUBSCRIPTION_guid/resourceGroups/myRG/providers/Microsoft.Compute/virtualMachines/myVM'
Get-AzureRmMetricDefinition –ResourceId $resourceId `
-DetailedOutput
https://blogs.msdn.microsoft.com/cloud_solution_architect/2016/02/26/retrieving-resource-metrics-and-creating-alert-rules-via-azure-powershell
Example 4: Get all resources with a given name
PowerShell = Copy ( Try It
PS C:\> Get-AzureRmResource -Name testVM | fl
Name : testVM
ResourceGroupName : testRG
ResourceType : Microsoft.Compute/virtualMachines
Location : westus
ResourceId : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/testRG/providers/Microsoft.Compute/virtualMachines/testVM
Example 7: Get a resource by resource id
PowerShell = Copy ( Try It
PS C:\> Get-AzureRmResource -ResourceId /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/testRG/providers/Microsoft.Compute/virtualMachines/testVM
Name : testVM
ResourceGroupName : testRG
ResourceType : Microsoft.Compute/virtualMachines
Location : westus
ResourceId : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/testRG/providers/Microsoft.Compute/virtualMachines/testVM
https://learn.microsoft.com/en-us/powershell/module/azurerm.resources/get-azurermresource?view=azurermps-6.7.0
Currently, it seems that there is no powershell command to get the Azure AD Audit and Sign-In logs directly.
If Micorsoft Graph Rest API is acceptable, you could use the following Microsoft graph Rest API to do that.
GET tenant user activities https://graph.microsoft.com/beta/auditLogs/directoryAudits
GET tenant user sign-ins https://graph.microsoft.com/beta/auditLogs/signIns
We also could get the demo code from this link.
If we want to run the code. We need to do prerequisites to access the Azure Active Directory reporting API, for more information please refer to this document.
$URIfilter = "?`$filter=activityDateTime gt $PastPeriod"
$url = "https://graph.microsoft.com/beta/auditLogs/directoryAudits" + $URIfilter
GetReport $url "DirectoryAudits" $Tenantdomain
For more information about Azure AD report, please refer to this tutorial
Update:
We could use the following Rest API to enable/update the Azure Audit logs or Sign-In logs.
Put https://management.azure.com/providers/microsoft.aadiam/diagnosticSettings/{name}?api-version=2017-04-01-preview
Body
{
"properties": {
"logs": [
{
"category": "AuditLogs",
"enabled": true,
"retentionPolicy": {
"days": 0,
"enabled": false
}
},
{
"category": "SignInLogs",
"enabled": true,
"retentionPolicy": {
"days": 0,
"enabled": false
}
}
],
"metrics": [],
"storageAccountId": "/subscriptions/{subscriptionId}/resourceGroups/{resourgroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}"
}
I test it with postman.

Resources