Acehaidrey commented on a change in pull request #18916:
URL: https://github.com/apache/airflow/pull/18916#discussion_r733229988
##########
File path: airflow/cli/commands/role_command.py
##########
@@ -42,3 +44,43 @@ def roles_create(args):
for role_name in args.role:
appbuilder.sm.add_role(role_name)
print(f"Added {len(args.role)} role(s)")
+
+
+@suppress_logs_and_warning
+def roles_export(args):
+ """
+ Exports all the rules from the data base to a file.
+ """
+ from airflow.www.security import EXISTING_ROLES
+ appbuilder = cached_app().appbuilder
+ roles = appbuilder.sm.get_all_roles()
+ exporting_roles = [role.name for role in roles if role.name not in
EXISTING_ROLES]
+ with open(os.path.expanduser(args.export), 'w') as file:
+ file.write(json.dumps(exporting_roles, sort_keys=True, indent=4))
+ print(f"{len(exporting_roles)} roles successfully exported to
{file.name}")
+
+
+@cli_utils.action_logging
+@suppress_logs_and_warning
+def roles_import(args):
+ """
+ Import all the roles into the db from the given json file.
+ """
+ json_file = getattr(args, 'import')
+ if not os.path.exists(json_file):
+ print(f"File '{json_file}' does not exist")
+ exit(1)
+
+ role_list = None
+ try:
+ with open(json_file, 'r') as file:
+ role_list = json.loads(file.read())
+ except ValueError as e:
+ print(f"File '{json_file}' is not a valid JSON file. Error: {e}")
+ exit(1)
+ appbuilder = cached_app().appbuilder
+ existing_roles = [role.name for role in appbuilder.sm.get_all_roles()]
+ roles_to_import = [role for role in role_list if role not in
existing_roles]
+ for role_name in roles_to_import:
+ appbuilder.sm.add_role(role_name)
Review comment:
Sorry I think I am not clear on this suggestion quite yet if you had
some more clarity for it.
So this function the idea is that it will import all the role names. The
permissions associated with each role are not actually exported or imported. So
when we call `add_role` for each of the roles that we are importing the
add_role function only imports it if that role doesn't exist on the cluster, so
it will not overwrite it at all.
```
def add_role(self, name: str) -> Optional[Role]:
role = self.find_role(name)
if role is None:
try:
role = self.role_model()
role.name = name
self.get_session.add(role)
self.get_session.commit()
log.info(c.LOGMSG_INF_SEC_ADD_ROLE.format(name))
return role
except Exception as e:
log.error(c.LOGMSG_ERR_SEC_ADD_ROLE.format(str(e)))
self.get_session.rollback()
return role
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]