After the roles are created, I need to map users into the roles — using the ElasticSearch API to list all roles and add each user to the corresponding OpenSearch role.
import requests
from requests.auth import HTTPBasicAuth
def addUserToRole(strRole, strUID):
jsonAddUser = [
{ "op": "add", "path": f"/{strRole}", "value": {"users": strUID} }]
print(f"{strRole}\t{jsonAddUser}")
r2 = requests.patch(f"https://opensearch.example.com:9200/_plugins/_security/api/rolesmapping", json=jsonAddUser, auth = HTTPBasicAuth('something', 'something'), verify=False)
print(r2.text)
print(r2.status_code)
listIgnoredGroups = ['security_rest_api_access', 'logstash_role', 'elastalert_role', 'kibana_server', 'wsadmin_role', 'mgmt_role', 'logstash', 'manage_snapshots', 'readall', 'all_access', 'own_index', 'kibana_user', ]
# Get all roles from prod & list users in those roles
#GET _opendistro/_security/api/rolesmapping/
r = requests.get(f"https://elasticsearch.example.com:9200/_opendistro/_security/api/rolesmapping/", auth = HTTPBasicAuth('something', 'something'), verify=False)
dictAllRoles = r.json()
# For each role, list out each user and add that user to that role in OS
for item in dictAllRoles.items():
if item[0] not in listIgnoredGroups:
for strUID in item[1].get('users'):
addUserToRole(item[0], item[1].get('users'))