Problem
I have an azure pipeline YAML file. It is able to run through a service connection which accesses a service principal with all the proper authority, etc.
But I am now trying to clean up the code; we have multiple service principals running on multiple subscriptions and resource groups. They need to create storage accounts, which need to be unique.
So I am trying to create a storage account built partially from the associated subscription and resource group of the service principal creating the storage account.
Example Solution
For the subscription, it is fairly easy. I can do something like this, from within a PowerShell script called inside the pipeline:
$subscriptionId = $(az account show --query 'id' -o tsv)
Write-Output "##vso[task.setvariable variable=AZURE_SUBSCRIPTION_ID;isoutput=true;issecret=true]$subscriptionId"
Now I have the variables $subscription ID and AZURE_SUBSCRIPTION_ID set, and can access subscription information within the pipeline itself.
Question
But how can I do something similar with resource groups?
There is no equivalent to az account show with resource groups, without knowing the resource group name itself. (Eg, I have to type az group show -name <RG-name>, but it is precisely the name that I am trying to get.)
Again, to be clear, I am running inside of a particular resource group and subscription, it is those that are associated with the service connection. Now I simply want that information available to the pipeline.
I'm not sure if I completely understand what you are trying to accomplish. But I suspect that the options below might help.
Get role assignments
If you created separate service connections for each individual resource group you can simply check the role assignments for the SPN and determine the scope of the service connection.
If you, for example, use the Azure PowerShell task, you have configured it with a Service Connection. So when the task starts, it has the context of the service principal. You can then do Get-AzRoleAssignment which should output the Resource Groups to which its authorised. Again, this is only useful if you use a service connection per RG, as you otherwise get results for multiple RGs. (Or for subscriptions and Management groups, if you also assigned a role to those scropes)
Use the Azure DevOps API
You can use the Get Service Endpoint request of the Azure DevOps API to get the service connections. The JSON output will contain information regarding the scope of the service connection.
If you find working with the API directly a bit hard, you can try the PSDevOps PowerShell module to interact with the Azure DevOps API. It has the Get-ADOServiceEndpoint command that allows you to get the available service endpoints.
Related
I'm an owner of an Azure resource group but not have permissions on the subscription or on the management group.
When configuring the "azurerm" provider inside my .tf file, I've added subscription id and tenant id (I'm not the owner of that subscription).
--------------------- UPDATE ---------------------
I'm trying to apply Linux virtual machine using Terraform but having authorization issues while planning the .tf file.
I've listed all my accounts using Azure CLI (want to connect the second subscription in the output below):
I've succeeded authenticating to the subscription using Azure CLI with the command (it worked):
az account set --subscription="SUBSCRIPTION_ID"
It's my default and current subscription:
Also, I was able to create and manage resources inside my resource group in that subscription using Azure CLI.
However, I added the exact tenant ID and the exact subscription ID inside my .tf file and still got the same credentials errors during the "terraform plan".
Using Azure CLI or Azure portal I am able to create and manage resources inside the resource group's scope, although using terraform I'm facing problems.
Thank you :)
According to your story, you just set the tenant id and subscription id in the azure provider, so it seems you authenticate via Azure CLI. No matter you have a user account or a service principal, the owner role of the resource group is enough to create virtual machine in the resource group. In this way, you need to logging into the Azure CLI first. As it shows in the link I have provided.
I have multiple subscriptions in an Azure tenant and I'd like to list all resources (IP addresses, VMs, etc) in the tenant. Is this the same as listing the resources from all subscriptions?
We can easily list all resources in a subscription with a service principal to access it. However, there are some problems when you try to do this for a tenant. It it possible to create a service principal or an equivalent that applies to the whole tenant or to all the subscriptions in the tenant (depending on the answer to the first question) that would allow to list all resources with a script?
EDIT:
Actually, what I'm precisely trying to do is to list all public IPs in a Azure tenant with a python script:
def get_public_ips(self):
"""#returns: All public ip adresses in the ressource defined by the service principal"""
ips=[]
rmc = get_client_from_auth_file(ResourceManagementClient, auth_path=PATH+"azure_creds.json")
for r in rmc.resources.list(filter="resourceType eq 'Microsoft.Network/publicIPAddresses'", expand='True'):
#There were no way to get the ip adress directly...
ip = rmc.resources.get_by_id(r.id, "2019-09-01")
ips.append(ip.properties['ipAddress'])
return common.sanitize_ips_list(ips)
The script can already list all IPs but it is using a service principal to authenticate: https://learn.microsoft.com/en-us/python/api/msrestazure/msrestazure.azure_active_directory?view=azure-python
I wonder how to do the same thing with a whole tenant. Is this event possible? Would the same script script work by simply using another way to authenticate, i.e.by using an authentication entity that has reading rights on the whole resources of the tenant?
Thanks
you can use tags and filter by tags
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-using-tags
The following command will return you all resources in your tenant:
az resource list
The following command will return you all public ip addresses in your tenant:
az resource list --resource-type 'Microsoft.Network/publicIPAddresses'
az resource show --ids '<resource id>'
Field 'properties.ipAddress' is likely what you are looking for.
When running an Azure Powershell task in an Azure DevOps Release Pipeline with system.debug=true, you will get an output similar to this:
# anonymized
...
2019-09-05T12:19:41.8983585Z ##[debug]INPUT_CONNECTEDSERVICENAMEARM: '7dd40b2a-1c37-4c0a-803e-9b0044a8b54e'
2019-09-05T12:19:41.9156487Z ##[debug]ENDPOINT_URL_7dd40b2a-1c37-4c0a-803e-9b0044a8b54e: 'https://management.azure.com/'
2019-09-05T12:19:41.9188051Z ##[debug]ENDPOINT_AUTH_7dd40b2a-1c37-4c0a-803e-9b0044a8b54e: '********'
2019-09-05T12:19:41.9221892Z ##[debug]ENDPOINT_DATA_7dd40b2a-1c37-4c0a-803e-9b0044a8b54e: '{"subscriptionId":"b855f753-d5b3-48f4-b7cd-5beb58fb5508","subscriptionName":"Entenhausen","environment":"AzureCloud","creationMode":"Automatic","azureSpnRoleAssignmentId":"5ddcc3fe-f93c-4771-8041-50b49f76b828","azureSpnPermissions":"[{\"roleAssignmentId\":\"5ddcc3fe-f93c-4771-8041-50b49f76b828\",\"resourceProvider\":\"Microsoft.RoleAssignment\",\"provisioned\":true}]","spnObjectId":"76055cb6-3b75-4191-9309-306b32dad443","appObjectId":"e4b90b9d-7a73-42a3-ae6e-4daec910def4","environmentUrl":"https://management.azure.com/","galleryUrl":"https://gallery.azure.com/","serviceManagementUrl":"https://management.core.windows.net/","resourceManagerUrl":"https://management.azure.com/","activeDirectoryAuthority":"https://login.microsoftonline.com/","environmentAuthorityUrl":"https://login.windows.net/","graphUrl":"https://graph.windows.net/","managementPortalUrl":"https://manage.windowsazure.com/","armManagementPortalUrl":"https://portal.azure.com/","activeDirectoryServiceEndpointResourceId":"https://management.core.windows.net/","sqlDatabaseDnsSuffix":".database.windows.net","AzureKeyVaultDnsSuffix":"vault.azure.net","AzureKeyVaultServiceEndpointResourceId":"https://vault.azure.net","StorageEndpointSuffix":"core.windows.net","EnableAdfsAuthentication":"false"}'
2019-09-05T12:19:41.9284444Z ##[debug]AuthScheme ServicePrincipal
...
I need to add the SPN of the Azure DevOps connection to a resource. When changing subscriptions or pipelines, the SPN also changes and I do not want to hardcode the value.
As the value is printed in the system.debug=true output, I am wondering how to access my own SPN within a pipeline task. Is it possible to read out spnObjectId":"76055cb6-3b75-4191-9309-306b32dad443" somehow using Powershell?
Information about the Service Principal can be accessed using Get-AzureRmContext but the information is limited and some is obfuscated in the logs so you need to make a second call to Get-AzureRmServicePrincipal to access the ObjectId
$Context = Get-AzureRmContext
$AzureDevOpsServicePrincipal = Get-AzureRmADServicePrincipal -ApplicationId $Context.Account.Id
$ObjectId = $AzureDevOpsServicePrincipal.Id
The Id exposed in $Context.Account.Id is the Service Principals ApplicationId
SPN within a pipeline task is nothing but the Azure subscription you have passed on to the task. You can click on manage connections and copy the details of the SPN under connections and use them as you need. But, I am not sure why do you want to use the SPN directly as you can always use an Azure Powershell Task and just select the subscription. Once you store the Connection, you can always reuse it in different pipelines.
We are building a solution in Azure Government and we will be using Terraform to deploy the solution. Seems the preferred method is to create a Service Principal for Terraform with the Service Principal having the Contributor role scoped to the subscription.
The one issue with this we are looking to solve is that this gives the Service Principal management plane access to the Key Vault...since it is in the subscription. With Contributor role, the service principal is not able to create new access policies (assign itself or others permissions to the data plane) but we are looking for a way that can remove the service principal from having any management plane permissions.
We have tried putting a ReadOnly lock on the Key Vault before creating the Service Principal but the lock does not stop the service principal from getting the Contributor permissions on the Key Vault.
Outside of creating a new role that has Contributor for everything EXCEPT for Key Vault, does anyone have any creative ideas that might help achieve this?
Yes, the root cause of all security issues is that the Service Principal's contributor role assignment is at the subscription level/scope, which enables it to do quite damage specially if multiple applications are deployed to the same subscription (e.g. delete any resource group).
One approach would be:
Provision one resource group for the Azure Key Vault specific to the application and region (the latter in case of geo-distributed applications).
Provision the Azure Key Vault on the resource group created on the previous step.
In our case, the Security Office was responsible for the first 2 steps, where they had monitoring (e.g. email, text-messages, etc.) for any change in the Azure Key Vault (e.g. new keys/secrets/certificates added/deleted/changed, permission changes, etc.).
Provision a second resource group, which will serve as a container for the application components (e.g. Azure Function, Azure SQL Server/Database, Azure Service Bus Namespace/Queue, etc.).
Create the Service Principal and assign the Contributor role to the
application resource group only, for example:
scope =
/subscriptions/{Subscription Id}/resourceGroups/{Resource Group
Name}
Find a sample PS script to provision a Service Principal with custom scope at https://github.com/evandropaula/Azure/blob/master/ServicePrincipal/PS/Create-ServicePrincipal.ps1.
Give appropriate permissions for the Service Principal in the Azure
Key Vault. In our case, we decided to have separate Service
Principal accounts for deployment (Read-Write permissions on keys/secrets/certificates) and runtime (Read-Only permissions on keys/secrets/certificates);
Find a sample PS script to set Service Principal permission on an Azure Key Vault at https://github.com/evandropaula/Azure/blob/master/KeyVault/PS/Set-ServicePrincipalPermissions.ps1.
Having that said, there are lots of inconveniences with this approach, such as:
The process (e.g. via runbook) to provision the Azure Key Vault (including its resource group) and the application resource group will be outside of the main Terraform template responsible for the application components, which requires coordination with different teams/processes/tools/etc.
Live site involving connectivity often involves coordination among multiple teams to ensure RTO and MTTM (Mean Time To Mitigate) goals are achieved.
The Service Principal will be able to delete the application specific resource group when terraform destroy is executed, but it will fail to recreate it when running terraform apply after that due to lack of permission at the subscription level/scope. Here is the error:
provider.azurerm: Unable to list provider registration status, it is possible that this is due to invalid credentials or the service principal does not have permission to use the Resource Manager API, Azure error: resources.ProvidersClient#List: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailed" Message="The client '' with object id '' does not have authorization to perform action 'Microsoft.Resources/subscriptions/providers/read' over scope '/subscriptions/{Subscription Id}'.".
Yeah, I know, this is a long answer, but the topic usually requires lots of cross-team discussions/brainstorming to make sure the security controls established by the Security Office are met, Developer productivity is not affected to the point that it will impact release schedules and RTO/MTTM goals are met. I hope this helps a bit!
I was trying to invoke data factory pipeline from azure function programmatically. Its throwing following error.
link:
http://eatcodelive.com/2016/02/24/starting-an-azure-data-factory-pipeline-from-c-net/
AuthorizationFailed: The client 'XXXX-XXXXX-XXXX' with object id 'XXX829e05'XXXX-XXXXX' does not have authorization to perform action
'Microsoft.DataFactory/datafactories/datapipelines/read' over scope
'/subscriptions/XXXXXX-4bf5-84c6-3a352XXXXXX/resourcegroups/fffsrg/providers/Microsoft.DataFactory/datafactories/ADFTestFFFS/datapipelines/ADFTutorialPipelineCustom'.
tried to search similar issues, but none of the search result gave me solution to my problem, Can you please guide us what could be the issue?
Objective is to, run data factory pipeline whenever file being added to blob. so to achieve the result we are trying to invoke data factory pipeline from azure function using blob trigger.
Step 1: login to your azure portal
Step 2: find Subscriptions in left side menu bar and click.
step 3: Click on Access Control IAM and then click on Add.
Step 4: In Add Permission window, select contributor for role. In select input box, type the app name you created in Azure AD (Created in Azure Active Directory)and select it. In my case I created Azure Resource Management.
Step 5:After you have given successful permission, click on Refresh in your subscription window and you will see your app showing in the list. See below example.
SEE Common problem when using Azure resource groups & RBAC
https://blogs.msdn.microsoft.com/azure4fun/2016/10/20/common-problem-when-using-azure-resource-groups-rbac/
This issue is more likely to happen in newer subscriptions and usually happens if a certain resource type has never been created before in that subscription.
Subscription admins often fix this issue by granting resource group owners contributor rights on the subscription level which contradicts with their strategy of isolating access down to the level of resource group level not the subscription level.
Root cause
Some admins say, that some resources require access to the subscription level to be able to create these resources and that ‘owner’ rights on a resource group level is not sufficient. That is not true.
Let’s take a step back to understand how this all works first.
To provision any resources in azure (using the resource manager model) you need to have a resource provider that supports the creation of that resource. For example, if you will provision a virtual machine, you need to have a ‘Microsoft.Compute’ resource provider available in the subscription first before you can do that.
Resource providers are registered on the level of the subscription only.
Luckily, the Azure Resource Manager (ARM) is intelligent enough to figure that out for you. When a new Azure resource gets provisioned, if the resource provider required for that resource type is not registered in the subscription yet, ARM will attempt to register it for you. That action (resource provider registration) requires access to the subscription level.
By default, any new azure subscription will be pre-registered with a list of commonly used resource providers. The resource provider for IoTHub for instance, is not one of them.
When a user is granted owner rights only on a specific resource group, if that user tries to provision a resource that requires registering a resource provider for the first time, that operation will fail. That is what happened in our case above when trying to provision IoThub.
So the bottom line is, we DO NOT need to grant access permissions to the subscription level for users to be able to create resources like HDInsight, IotHub and SQLDW …etc within their resource groups that they have owner rights on, as long as the resource providers for these resources is already registered.
You get the error that you are not authorized to perform action 'Microsoft.DataFactory/datafactories/datapipelines/read' over scope of pipeline because you don't have the relevant permissions on the datafactory.
You either need to have "Contributor" /"DataFactoryContributor" permissions to create & manage data factory resources or child resources. More details of the azure RBAC roles in the following link:
https://learn.microsoft.com/en-us/azure/active-directory/role-based-access-built-in-roles
Since the customer is trying to use the ADF client from inside Azure Function, the recommendation is to use AAD application and service principal for authentication of ADF client. You can find the instructions for creating AAD application and service principal here:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal
Please follow the instructions on how to create the Active Directory application, service principal, and then assign it to the Data Factory Contributor role in the following link and the code sample for using service principal with ADF client.
We recently had this issue with the same message and found that it was caused by the user being logged in with a different subscription (we have 2). Using az login --subscription resolved the problem for us.
For anyone else running into a similar issue with the same error message - After "az login" I was recieving the same error when attempting to create a resource group as Owner, I solved this with:
az account set --subscription "Azure Subscription 1"
Basically it stems from the subscription not being set, you can find the details here:
https://learn.microsoft.com/en-us/cli/azure/manage-azure-subscriptions-azure-cli#get-the-active-subscription
Solution:
Step 1: Register an app in Azure Active directory.
Step 2: Assign 'Data Factory Contributor' role to the same app. we can achieve this by using power shell.
The below code works for me. Please try out in power shell after logged in with Azure credential.
Implementation:
Step 1: $azureAdApplication = New-AzureRmADApplication -DisplayName <AppName> -HomePage <URL> -IdentifierUris <URL with domain> -Password <Password>
Step 2: New-AzureRmRoleAssignment -RoleDefinitionName "Data Factory Contributor" -ServicePrincipalName $azureAdApplication.ApplicationId
Follow this post : https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal
In this post , Role is given as "Reader" which should be "Owner" instead otherwise it would give permission error on deployment.
I solved by following this post:
https://www.nwcadence.com/blog/resolving-authorizationfailed-2016
with the command in PowerShell:
Get-AzureRmResourceProvider -ListAvailable | Select-Object ProviderNamespace | Foreach-Object { Register-AzureRmResourceProvider -ProviderName $_.ProviderNamespace}
I solved by finding the Enterprise Application > Object ID.
(it is weird that it does not use App Reg > Application Id)
https://jeanpaul.cloud/2020/02/03/azure-data-factory-pipeline-execution-error/