How do I automatically create service principals or MSIs with Terraform for use in Azure Pipelines to manage AKS resources? - azure-devops

I'm following the official docs to create Azure Kubernetes clusters. The docs state that I need to create a service principal first, manually, and provide the client_id and client_secret.
Doing it manually is not an option.
Here is the code for my service principal. It's decorated with links to the most recent Terraform docs for reference.
data "azurerm_subscription" "current" {}
data "azuread_client_config" "current" {}
resource "random_id" "current" {
byte_length = 8
prefix = "ExternalDnsTf"
}
# Create Azure AD App.
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application
resource "azuread_application" "current" {
display_name = random_id.current.hex
owners = [data.azuread_client_config.current.object_id]
}
# Create Service Principal associated with the Azure AD App
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal
resource "azuread_service_principal" "current" {
application_id = azuread_application.current.application_id
app_role_assignment_required = false
owners = [data.azuread_client_config.current.object_id]
}
# Create Service Principal password
# https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/application_password
resource "azuread_application_password" "current" {
application_object_id = azuread_application.current.object_id
}
# Create role assignment for service principal
# https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/role_assignment
resource "azurerm_role_assignment" "current" {
scope = data.azurerm_subscription.current.id
role_definition_name = "Contributor"
# When assigning to a SP, use the object_id, not the appId
# see: https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-cli
principal_id = azuread_service_principal.current.object_id
}
I keep getting the following error in my pipeline: (note, I am the owner of my subscription)
ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData
│ error: Authorization_RequestDenied: Insufficient privileges to complete the
│ operation.
What I'm trying to do is to eliminate the manual steps to setup supporting services. Take ExternalDNS for example. The Azure docs state that I need to use az ad sp create-for-rbac -n ExternalDnsServicePrincipal; az role assignment create --role "Reader" --assignee <appId GUID> --scope <resource group resource id>; az role assignment create --role "Contributor" --assignee <appId GUID> --scope <dns zone resource id>
Ultimately, I'm trying to create the terraform version of the azure cli commands.
Support for create-for-rbac was a feature request on github. That used to work great, but so much has changed, it's not applicable to current API versions. Also, with AAD Graph being deprecated in favor Microsoft Graph API, I wonder if I'm getting snagged on that.
The ExternalDNS docs also suggested Managed Service Identities (MSI). Service principals, MSI, MSGraph API integration, honestly, I don't care which one is used. Whatever is current best-practices is fine so long as I do not have to log into the portal to manually create or give permissions, or manually run az cli commands.
EDIT: Permissions clarification
I'm using Terraform, of course, to provision resources. If I do all of this without terraform (manually or with a bash script), I use azure cli I start setting permissions by doing the following:
az login
az account set -s <my-subscription-id>
I am the owner of my subscription. I can run all commands, create SPs, MSIs, assign roles, etc, with no problem.
In the pipelines, I am using the charleszipp az pipelines terraform plugin. In the logs, I see:
az login --service-principal -t <my-tenant-id> -u *** -p ***
az account set -s <my-subscription-id>
I'm not sure if that makes a difference. I interpret that as ultimately, commands are executed after signing in and setting the account subscription, like I do manually.
Technically, I'm not using a service connection in several of these tasks. However, where one is required, I have created a Service connection and defined its Scope to the subscription level. It's of type Azure Resource Manager.
However, if I click "manage service principal, it takes me to the portal where there are no permissions defined.
While I am the owner of my subscription, I am not the root management group. I'm owned / provisioned by someone else. Ultimately, they have control of Active Directory. I cannot add or edit permissions. If I try to add any under permissions API and select Microsoft Graph, it says that authorization is required. Grant Admin Consent for <parent organization is greyed out.
But why would that be important if I'm the owner of my subscription? If I can do whatever I want via the az cli command line, what's preventing me from doing the same in the pipeline?

I am using user-managed identity for that, it seemed most straightforward and worked fine for me.
resource "azurerm_user_managed_identity", "mi" {
resource_group_name = "rg"
name = "mi"
location = "eastus"
}
resource "azurerm_role_assignment" "ra" {
scope = azurerm_subnet.sn.id // subnet I created earlier
role_definition_name = "Network Contributor" // required with kubenet
principal_id = azurerm_user_managed_identity.mi.principal_id
}
resource "azurerm_kubernetes_cluster" "aks" {
name = "aks"
identity {
type = "UserAssigned"
user_assigned_identity_id = azurerm_user_managed_identity.mi.id
}
<...remaining attributes...>
depends_on = [azurerm_role_assignment.ra] // just to be safe
}

Related

Azure Release Pipeline does not have enough permissions to deploy Bicep/ARM template

When I try to deploy my Bicep template through a DevOps release pipeline I get the following error:
Deployment failed with multiple errors: 'Authorization failed for
template resource '1525ed81-ad25-486e-99a3-124abd455499' of type
'Microsoft.Authorization/roleDefinitions'. The client
'378da07a-d663-4d11-93d0-9c383eadcf45' with object id
'378da07a-d663-4d11-93d0-9c383eadcf45' does not have permission to
perform action 'Microsoft.Authorization/roleDefinitions/write' at
scope
'/subscriptions/8449f684-37c6-482b-8b1a-576b999c77ef/resourceGroups/rgabpddt/providers/Microsoft.Authorization/roleDefinitions/1525ed81-ad25-486e-99a3-124abd455499'.:Authorization
failed for template resource '31c1daec-7d4a-4255-8528-169fc45fc14d' of
type 'Microsoft.Authorization/roleAssignments'.
I understand through this post that I have to grant "something" the Owner or User Access Administrator role.
But I don't understand what user has the ObjectId 378da07a-d663-4d11-93d0-9c383eadcf45.
I tried to look it up with the following az CLI command, but it says that it cannot find a resource with that Id:
az ad user show --id 378da07a-d663-4d11-93d0-9c383eadcf45
The response it returns:
Resource '378da07a-d663-4d11-93d0-9c383eadcf45' does not exist or one of its queried reference-property objects are not present.
I'm a but clueless here. What do I exactly have to grant permission?
When you use service connection in DevOps pipeline, for example Azure Resource Manager service connection, it will create a service principal(app registry) on Azure portal-> Active Directory. You can find the service principal by clicking the link on service connection:
When you deploy with service connection, please make sure you have give correct permission for this service principal on target resource, like mentioned Microsoft.Authorization/roleDefinitions/write. Suggest to give contributor role on the resource. Otherwise it will reports the error in your pipeline log.
When you add the role, you will find the object id, it's different with service principal application ID or object id.
It's azure role not Azure AD role. You can find the difference in the doc.

Azure Bicep - Unable to create a Management Group

I am in the process of trying to learn Bicep, as a part of that self-instruction I have been trying unsuccessfully to create a management group hierarchy. I am attempting to create a single management group using the following but am getting an error message when I deploy the bicep file.
targetScope = 'tenant'
param mgName string = 'test-displayname'
resource mgmtGroup 'Microsoft.Management/managementGroups#2021-04-01' = {
name: mgName
}
When I attempt to deploy I get the following error message:
"Deployment failed for c:\bicep\Management Groups\azuredeploy.bicep. Tenant scope deployment is not currently supported."
I have tried changing API versions, deploying to the management group scope, etc. all with no success.
Any ideas are greatly appreciated!
Thanks
By default, the SPN does not have permission to deploy tenant resources. You need to grant it at the root scope "/" to make it work.
First, you need to elevate your permissions as user Global Administrator into Azure AD:
https://learn.microsoft.com/en-us/azure/role-based-access-control/elevate-access-global-admin
Connect-AzAccount
$user = Get-AzADUser -SignedIn
New-AzRoleAssignment -Scope '/' -RoleDefinitionName 'Owner' -ObjectId $user.Id
Now you are able to set your SPN with the correct permissions:
https://github.com/Azure/Enterprise-Scale/blob/main/docs/EnterpriseScale-Setup-azure.md
$spndisplayname = "<SPN Display Name>"
$spn = (Get-AzADServicePrincipal -DisplayName $spndisplayname).id
New-AzRoleAssignment -Scope '/' -RoleDefinitionName 'Owner' -ObjectId $spn
I think you may be running into a few different issues.
How are you deploying the template? The error you posted doesn't sound like it's coming from the service but the client...
Your bicep file is targeting the tenant scope, for that you need permission to create template deployments at tenant scope (even if you create no resources). The principal deploying the template will need permission (contributor at least, owner is not required) at the tenant scope as Wesley mentioned. The thing to be aware of here is that this gives that principal contributor access to everything in the tenant - all MGs, All subs, All RGs. It's very permissive and needs to be used carefully/sparingly. Also, note that you do not need to target the tenant scope to create the MG in a template. You can set the targetScope in bicep to a RG, Sub or MG. But the principal deploying the template must have permission at whatever scope you target the bicep file to.
A principal need not be given any special permission to simply create a MG - all users have this permission. You can test this by creating an MG on the cmd line. When that user creates the MG, the user is made the "owner" of that MG.
Point being, be very careful about granting perms at the tenant level and use only when necessary.
All that said, if your goal is to create MGs and deploy resources to those MGs in the same bicep deployment, the best path is to give the principal permissions (contributor is best) at the tenant level. Otherwise you will run into replication delays with permissions on the newly created MGs.
HTH

With MS Graph API, how do I force my programmatically created Service Principals, MSIs, and IaC code to be scoped to my subscription only?

Active Directory Graph API is now fully deprecated, in favor of MS Graph API.
My company has given me my own Visual Studio Professional subscription. I also have a DevOps organization. I am the Owner role in both.
with AADG API, I could use Terraform, for example, to create Service Principals and manage roles. Service Connections in DevOps were scoped to my subscription.
Example:
## These are in my resource group
...
resource "azuread_service_principal" "example" {
application_id = azuread_application.example.application_id
app_role_assignment_required = false
owners = [data.azuread_client_config.current.object_id]
}
...
resource "azurerm_role_assignment" "kubweb_to_acr" {
scope = azurerm_container_registry.acr.id
role_definition_name = "AcrPull"
principal_id = azurerm_kubernetes_cluster.kubweb.kubelet_identity[0].object_id
}
This used to work great. Now it does not. Now I get errors like:
Error: authorization.RoleAssignmentsClient#Create: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailed" Message="The client '3520c717-e1cc-4d0b-b021-2f93a1b05d80' with object id '3520c717-e1cc-4d0b-b021-2f93a1b05d80' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write
and
ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData
│ error: Authorization_RequestDenied: Insufficient privileges to complete the
│ operation.
Even though I own my subscription, there is a parent organization above me. My SPs get scoped to their AD where I can't manage them. I can't use "Grant Admin Consent" through MS Graph API. Also, in DevOps, when I create an ARM Service Connection, for example, I scope it to my Subscription. It never scopes to my subscription, but the parent's, and I can't change its permissions.
How do I alter my development or scope my resources so that I don't have to defer to parent organization?
What role do they need to give me so I don't have to involve them?
I'm already the owner of my subscription. How do I create these types of resources in a way that I have full control over managing them again?
Side-note, it's interesting. I can use Azure CLI and run the same commands via terminal, and I have no problems creating or altering resources. The same commands az ad sp create-for-rbac don't throw any errors at all, and it's using the same permissions and scope defined in the pipelines.
Both errors you show are due to the service principal that Terraform is running as has not been authorized to perform the action in question. (From the Azure role assignment error, we can know this is the service principal with object ID "3520c717-e1cc-4d0b-b021-2f93a1b05d80".)
To assign an Azure role to a user, group, or service principal (your first error), the service principal used by Terraform needs to be have been granted a role that includes the "Microsoft.Authorization/roleAssignments/write" operation, scoped to (at least) scope you're trying to grant the role at (e.g. the specific Azure resource, the resource group it's in, or the subscription it's in). Typically, if you need to create Azure role assignments, this is the "Owner" role. More details from Terraform in Allowing the Service Principal to manage the Subscription. If you're "Owner" of the Azure subscription, then you will be able to do this yourself.
To create Azure AD application and service principals (your second error): The service principal used by Terraform needs to be granted permission to do this in the Azure AD tenant in question. For example, the app roles (application permissions) Application.Read.All and Application.ReadWrite.OwnedBy would suffice in many cases. These are actions that take place in the Azure AD tenant, so an Azure AD administrator will need to grant this access—you cannot do this on your own if you're not an admin of the Azure AD tenant. More details from Terraform in Configuring a User or Service Principal for managing Azure Active Directory.
How do I alter my development or scope my resources so that I don't have to defer to parent organization?
You could have an entirely separate Azure AD tenant (where you'd be administrator), and point the Azure subscription to trust that tenant. This may or may not be compatible with your organization's policies and practices.
I'm already the owner of my subscription. How do I create these types of resources in a way that I have full control over managing them again?
Azure AD applications and service principals are not a part of your Azure subscription, they're in the "parent" Azure AD tenant. You (the user) probably do have permission over these objects (e.g. you're owner of them in Azure AD), but Terraform isn't running as you—it's running as a separate service principal.
Side-note, it's interesting. I can use Azure CLI and run the same commands via terminal, and I have no problems creating or altering resources. The same commands az ad sp create-for-rbac don't throw any errors at all, and it's using the same permissions and scope defined in the pipelines.
You're probably connecting to Azure CLI as yourself (i.e. your user account), instead of the service principal Terraform is using. If you connect to Azure CLI using the same service principal (e.g. az login --service-principal ...), you'd likely experience the same errors, because that service principal hasn't been granted privileges over the Azure AD tenant and the Azure subscription yet.

Azure Terraform Unable to Set secret in KeyVault during deployment

I am facing a blocker that I don't seem to find a practical solution.
I am using azure terraform to create a storage account, and I would like, during the release pipeline, to be able to set the connection string of this storage account as a secret in an existing KeyVault.
So far I am able to retrieve secret from this KeyVault as I am using a managed identity which has the following permission upon the KeyVault:
key = get, list
secret = get, list and set
cert = get , list
the workflow process in my terraform is as follow:
Retrieve the KeyVault data:
data "azurerm_key_vault" "test" {
name = "test"
resource_group_name = "KeyVault-test"
}
Retrieve the user assigned identity data:
data "azurerm_user_assigned_identity" "example" {
name = "mng-identity-example"
resource_group_name = "managed-identity-example"
}
Once I have those 2 data, I tried to create the secret as follow:
resource "azurerm_key_vault_secret" "secretTest" {
key_vault_id = data.azurerm_key_vault.test.id
name = "secretTest"
value = azurerm_storage_account.storageaccount.primary_connection_string
}
Once I set the release pipeline to run this terraform, it does fail with the error Access Denied
Which is fully understandable as this terraform does not have permission to set or retrieve the secret.
And this is the part on which I am blocked.
If anyone can help understand how can I use my managed identity to set this secret?
I looked into terraform documentation but couldn't find any step or explanation.
Thank you so much for your help and time, and please if you need more info just ask me.
Please make sure that the service principal that you are using to login into Azure using Terraform has the same permission which you assigned to the managed identity .
provider "azurerm" {
features {}
subscription_id = "00000000-0000-0000-0000-000000000000"
client_id = "00000000-0000-0000-0000-000000000000" ## This Client ID needs to have the permissions in Keyvault access policy which you have provided to the managed identity.
client_secret = var.client_secret
tenant_id = "00000000-0000-0000-0000-000000000000"
}
OR
If You are using a Service Connection to connect the Devops Pipeline to Azure and use it in Terrafarom , then you need to provide that Devops service connection (service principal) the permissions in the access policy.

(ResourceGroupNotFound) Resource group '????' could not be found when creating an azure media services account

I'm trying to create a Service Principal account using the instructions here
https://learn.microsoft.com/en-us/azure/media-services/latest/stream-files-tutorial-with-api#examine-the-code-that-uploads-encodes-and-streams
However when I run the command
az ams account sp create --account-name *media_service_account_name* --resource-group *resource_group_name*
Where media_service_account_name is the name shown for the media service I have created and resource_group_name the name of the resource group shown on the same page.
The problem is I get the message ResourceGroupNotFound:
Resource group 'resource_group_name' could not be found.
I just can't see what I am doing wrong. Any help appreciated.
If you have multiple subscriptions, set your subscription first and then try:
To list all subscriptions - az account list --output table
To set your subscription - az account set --subscription <subscription-id>
I had the same issue and verified the subscription with az account show, but what I was missing is that I was working in powershell and needed to set the correct subscription in powershell.
Verify context: Get-Azcontext
Set context: Set-Azcontext <subscription_id>
You may have multiple subscriptions. Set the subscription to default which you want to use in CLI.
Reference: https://learn.microsoft.com/en-us/cli/azure/manage-azure-subscriptions-azure-cli?view=azure-cli-latest
Kindly follow these steps to get over an above error:
az login
It will ask you to provide credentials
az account list --o table // Will list all subscription
Set your subscription on which you want to execute query
3. az account set --subscription "VS Subscription"
Hope it will help
I was running a task: AzureCLI#2 in azure pipeline for creating an azure vwan.
I put az account set --subscription xxxxxxx-xxxx-xxx-xxxx-xxxxxxxxx but it still didn't work and was throwing:
ERROR: (ResourceGroupNotFound) Resource group 'test-rg' could not be found.
Then I added --subscription "xxxxxxx-xxxx-xxx-xxxx-xxxxxxxxx" at the end of he az network vwan create even though it wasn't shown in the documentation.
Here's how I did:
az network vwan create --name testwan01 --resource-group test-rg --subscription "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" --type Standard
Hope it helps if you are running it from some orchestration tools like Jenkins or Azure pipelines.
Keep in mind that Resource Groups in Azure are things that you create, so the article was only providing an example of a Resource Group name.
The command to create the service principal expects you to use the resource group that you used to create your media service account.
az ams account sp create --account-name amsaccount --resource-group **amsResourceGroup**
Make sure that you are using the right resource group name that you used when you created your Media Services account first, and use a unique named one in the same region as your account. I usually call az group create before creating a new account to put it into it's own Resource Group along with the storage account I create for it.
Example
Create a new resource group named "MyResourceGroup" in the West US region.
az group create -l westus -n
Hope that helps!