Terraform-provider-azurerm: Feature Request: Get object_id of current user

Created on 11 Apr 2019  ·  10Comments  ·  Source: terraform-providers/terraform-provider-azurerm

Community Note

  • Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Description

Terraform AzureRM provider currently supports getting the object ID of the logged in Service Principal, but not the object ID of the logged in user.

We can use the azurerm_client_config data source to get the current Service Principal object ID (service_principal_object_id). It would be nice to be able to get the current user object ID as well.

Use case: For currently logged in user to be able to self-assign permissions, for example when creating Key Vault. For reference Azure CLI does this when creating Key Vault using az keyvault create.

New or Affected Resource(s)

  • azurerm_client_config

Potential Terraform Configuration

data "azurerm_client_config" "current" {}

output "user_object_id" {
  value = "${data.azurerm_client_config.current.user_object_id}"
}

References

  • https://godoc.org/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac#SignedInUserClient

  • https://godoc.org/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac#User
  • enhancement servicauthentication

    Most helpful comment

    EDIT: Better version that also finds the user's Azure Active Directory Tenant ID

    Workaround

    Here's a workaround. Requires az cli to be present in the path.

    locals {
      #Hacky default but saves an extra data.external call. The two variables allow for working with a user who is not in the same AD tenant as the resource
      this_az_account_azuread_id = "${split("/",data.external.this_az_account.result.odata_metadata)[3]}"
      azure_active_directory_id = "${var.azure_active_directory_id != "azureactivedirectoryiddefault" ? var.name : local.this_az_account_azuread_id}"
    }
    
    #Allows for the azure AD tenant id to be overriden
    variable "azure_active_directory_id" {
      description = "The Directory ID of your Azure Active Directory, viewable in Properties on the Azure Portal. Defaults to the current Az CLI User's Account"
      default = "azureactivedirectoryiddefault"
    }
    
    #Fetch current user info using the AZ cli
    data "external" "thisAccount" {
      program = ["az","ad","signed-in-user","show","--query","{displayName: displayName,objectId: objectId,objectType: objectType}"]
    }
    
    resource "azurerm_key_vault" "this" {
      name                = "${local.name_prefix}"
      location            = "${var.location}"
      resource_group_name = "${azurerm_resource_group.this.name}"
      tenant_id           = "${local.azure_active_directory_id}"
      sku {
        name = "standard"
      }
    }
    
    resource "azurerm_key_vault_access_policy" "this" {
      vault_name          = "${azurerm_key_vault.this.name}"
      resource_group_name = "${azurerm_resource_group.this.name}"
      #Grant access to the terraform account for purposes of adding additional keys
      tenant_id = "${local.this_az_account_azuread_id}"
      object_id = "${data.external.this_az_account.result.objectId}"
      secret_permissions = [
        "set",
        "get",
        "list"
      ]
    }
    
    output "displayName" {
      value = "${data.external.thisAccount.result.displayName}"
    }
    output "objectId" {
      value = "${data.external.thisAccount.result.objectId}"
    }
    
    output "objectType" {
      value = "${data.external.thisAccount.result.objectType}"
    }
    
    output "userActiveDirectoryTenantID" {
      value = "${locals.this_az_account_azuread_id}"
    }
    

    All 10 comments

    hey @joakimhellum-in

    Thanks for opening this issue :)

    I'd agree with this, I've actually been meaning to look into this for a while, however I believe it should take a slightly different direction to what's proposed above; so that the same Terraform Configuration can be used both with a Service Principal or a User Account, whereas today a slightly different configuration has to be used which is confusing. As such I believe it'd be better to deprecate the existing service_principal_object_id field and introduce a new field object_id which returns the Object ID associated with the current authentication mechanism (either the Service Principal, or the logged in user) - what do you think?

    Thanks!

    @tombuildsstuff Yes, completely agree it would be better to introduce new field object_id that returns the object ID of current service principal, user or managed identity.

    My only justification for splitting this into service_principal_object_id and user_object_id is being able to determine if current object ID is a service principal or user. Example Terraform configuration for this:

    locals {
      service_principal_object_id = "${data.azurerm_client_config.current.service_principal_object_id}"
      user_object_id              = "${data.azurerm_client_config.current.user_object_id}"
    
      is_service_principal = "${local.service_principal_object_id != "" ? true : false}"
    }
    

    But after your comment and second thought I guess it's better to possibly introduce new field similar to user.type in output of az account show Azure CLI command. For example:

    Run az login to log in to Azure as user, and then run az account show (type is "user"):

    {
      "environmentName": "AzureCloud",
      "id": "ddab71c1-4649-46e2-8b63-9ecfb860c3fa",
      "isDefault": true,
      "name": "terraform-test-1",
      "state": "Enabled",
      "tenantId": "f4683495-fdad-496a-82fb-e2c3a24082f3",
      "user": {
        "name": "[email protected]",
        "type": "user"
      }
    }
    

    Run az login --service-principal -u http://terraform-test-1 -p ... to log in to Azure with service principal, and then run az account show (type is "servicePrincipal"):

    {
      "environmentName": "AzureCloud",
      "id": "ddab71c1-4649-46e2-8b63-9ecfb860c3fa",
      "isDefault": true,
      "name": "terraform-test-1",
      "state": "Enabled",
      "tenantId": "f4683495-fdad-496a-82fb-e2c3a24082f3",
      "user": {
        "name": "http://terraform-test-1",
        "type": "servicePrincipal"
      }
    }
    

    I don't have any use case for this other than doing a "who am I", meaning if object ID is user, then get user information from Azure AD.

    EDIT: Better version that also finds the user's Azure Active Directory Tenant ID

    Workaround

    Here's a workaround. Requires az cli to be present in the path.

    locals {
      #Hacky default but saves an extra data.external call. The two variables allow for working with a user who is not in the same AD tenant as the resource
      this_az_account_azuread_id = "${split("/",data.external.this_az_account.result.odata_metadata)[3]}"
      azure_active_directory_id = "${var.azure_active_directory_id != "azureactivedirectoryiddefault" ? var.name : local.this_az_account_azuread_id}"
    }
    
    #Allows for the azure AD tenant id to be overriden
    variable "azure_active_directory_id" {
      description = "The Directory ID of your Azure Active Directory, viewable in Properties on the Azure Portal. Defaults to the current Az CLI User's Account"
      default = "azureactivedirectoryiddefault"
    }
    
    #Fetch current user info using the AZ cli
    data "external" "thisAccount" {
      program = ["az","ad","signed-in-user","show","--query","{displayName: displayName,objectId: objectId,objectType: objectType}"]
    }
    
    resource "azurerm_key_vault" "this" {
      name                = "${local.name_prefix}"
      location            = "${var.location}"
      resource_group_name = "${azurerm_resource_group.this.name}"
      tenant_id           = "${local.azure_active_directory_id}"
      sku {
        name = "standard"
      }
    }
    
    resource "azurerm_key_vault_access_policy" "this" {
      vault_name          = "${azurerm_key_vault.this.name}"
      resource_group_name = "${azurerm_resource_group.this.name}"
      #Grant access to the terraform account for purposes of adding additional keys
      tenant_id = "${local.this_az_account_azuread_id}"
      object_id = "${data.external.this_az_account.result.objectId}"
      secret_permissions = [
        "set",
        "get",
        "list"
      ]
    }
    
    output "displayName" {
      value = "${data.external.thisAccount.result.displayName}"
    }
    output "objectId" {
      value = "${data.external.thisAccount.result.objectId}"
    }
    
    output "objectType" {
      value = "${data.external.thisAccount.result.objectType}"
    }
    
    output "userActiveDirectoryTenantID" {
      value = "${locals.this_az_account_azuread_id}"
    }
    

    If implementing a unified object ID for both user and service principal is too much, I'm thinking a simple if function would suffice for those who may need both.

    object_id = "${data.azurerm_client_config.current.service_principal_object_id != "" 
                    ? data.azurerm_client_config.current.service_principal_object_id 
                    : data.azurerm_client_config.current.object_id}"
    

    My use case is sometimes

    1. I will build a Key Vault with my account and I will need access.
    2. Other times a Service Principal through Azure DevOps will build the Key Vault and will need access.

    @JustinGrote fantastic workaround! Thanks a million! :-D

    2 minor points:

    • You've got thisAccount and this_az_account referring to the same thing;, possibly from before an edit? I don't think the example works in its current form, quite!
    • in the external data source, please add a -o=json param for folks who might have configured a non-JSON default output format :-)

    @jpluscplusm I think I've since refactored it to be way simpler in 0.12, may post that later if I have time.

    Any update on this? Trying to create an access policy for a keyvault and need to get the authenticated users object id.

    This has been released in version 1.35.0 of the provider. Please see the Terraform documentation on provider versioning or reach out if you need any assistance upgrading. As an example:

    provider "azurerm" {
        version = "~> 1.35.0"
    }
    # ... other configuration ...
    

    I'm going to lock this issue because it has been closed for _30 days_ ⏳. This helps our maintainers find and focus on the active issues.

    If you feel this issue should be reopened, we encourage creating a new issue linking back to this one for added context. If you feel I made an error 🤖 🙉 , please reach out to my human friends 👉 [email protected]. Thanks!

    Was this page helpful?
    0 / 5 - 0 ratings