Set permission to users during databricks notebook runtime

45 Views Asked by At

There is a notebook in databricks, certain business people dont have right to view the job runs. Only admins and one more group have access to view them. In the permissions section , I can set it manually so that some users to manage runs so they can see the job logs. But this is a manual work every time the notebook runs and i want to automate this task. How can i proceed ? I am using this script currently, but the response is 403

import requests
import json

# Databricks workspace URL
url = "https://<databricks-instance>/api/2.0/admin/users/create"

# Databricks API token
token = "<your-api-token>"

# Headers for the API request
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

# Function to add user to Databricks workspace
def add_user(username, email, display_name):
    payload = {
        "user_name": username,
        "email": email,
        "display_name": display_name,
        "password": "password"  # Change to the desired initial password
    }
    
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    
    if response.status_code == 200:
        print(f"User '{username}' added successfully.")
    else:
        print(f"Failed to add user '{username}'. Status code: {response.status_code}")
        print(response.text)

# Example usage
if __name__ == "__main__":
    # List of users to add
    users_to_add = [
        {"username": "user1", "email": "[email protected]", "display_name": "User One"},
        {"username": "user2", "email": "[email protected]", "display_name": "User Two"}
        # Add more users as needed
    ]
    
    for user in users_to_add:
        add_user(user["username"], user["email"], user["display_name"])
1

There are 1 best solutions below

0
JayashankarGS On

Use the following endpoint to create a new user: /api/2.0/accounts/{account_id}/scim/v2/Users

The request sample should look like this:

{
  "id": "string",
  "userName": "[email protected]",
  "emails": [
    {
      "$ref": "string",
      "value": "string",
      "display": "string",
      "primary": true,
      "type": "string"
    }
  ],
  "name": {
    "givenName": "string",
    "familyName": "string"
  },
  "displayName": "string",
  "roles": [
    {
      "$ref": "string",
      "value": "string",
      "display": "string",
      "primary": true,
      "type": "string"
    }
  ],
  "externalId": "string",
  "active": true
}

Make changes to your endpoint and payload. To obtain the account_id, follow this documentation.

Error 403 is related to authentication, so provide the correct token. However, you will still encounter an error with your current endpoint, so change it as mentioned above.