Is there a way with Azure Native to grant data acc...
# azure
p
Is there a way with Azure Native to grant data access to Cosmos DB to a managed identity?
m
I guess you just have to find the correct role id for cosmosdb data reader and do a role assignment with this role id, the id of your managed identity and the scope (your cosmos db account)
m
You can do it with a
SqlResourceSqlRoleAssignment
, not the usual
RoleAssignment
. Here's some C# code I use in a project. This one creates a custom role inside Cosmos DB with with
SqlResourceSqlRoleDefinition
object, then assigns it to a given principal using
SqlResourceSqlRoleAssignment
. In this case it assigns it to the System Assigned Identity of an Azure Function, but you can supply your managed id.
Copy code
//Allow the function app to read/write to Cosmos DB
//Make a custom role to access the database. Can't find a way to use a built in one, so we just make our own
var roleId = new Pulumi.Random.RandomUuid("my-role-id-uuid", new Pulumi.Random.RandomUuidArgs{ });
var roleAssignmentId = new Pulumi.Random.RandomUuid("my-role-assignment-id-uuid", new Pulumi.Random.RandomUuidArgs{ });

var cosmosDbContributorRole = new SqlResourceSqlRoleDefinition("arcade-device-management-cosmos-contributor", new AzureNative.DocumentDB.SqlResourceSqlRoleDefinitionArgs
{
    ResourceGroupName = ResourceGroupName,
    RoleName = "my-custom-contributor",
    AccountName = cosmosDBInfra.Account.Name,
    RoleDefinitionId = roleId.Result,
    Type = RoleDefinitionType.CustomRole,
    Permissions = new[]
    {
        new AzureNative.DocumentDB.Inputs.PermissionArgs
        {
            DataActions = new []
            {
                "Microsoft.DocumentDB/databaseAccounts/readMetadata",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*"
            }
        }
    },
    AssignableScopes = new[]
    {
        cosmosDBInfra.Account.Id
    }
});

_ = new SqlResourceSqlRoleAssignment("my-role-assignment", new AzureNative.DocumentDB.SqlResourceSqlRoleAssignmentArgs
{
    ResourceGroupName = ResourceGroupName,
    PrincipalId = functionPrincipalId,
    AccountName = cosmosDBInfra.Account.Name,
    RoleDefinitionId = cosmosDbContributorRole.Id,
    RoleAssignmentId = roleAssignmentId.Result,
    Scope = cosmosDBInfra.Account.Id
});
p
Thanks a lot @modern-quill-17695, that seems useful!