Features is pretty handy for stuff like this. However, if you do need to create roles and add permissions programmatically, you don't have to go digging through the database on your own.
When you create a new user role with user_role_save()
, it will update the object you passed in with the new user role id that was assigned. You can see an example of this in the standard_install()
function in the Standard installation profile.
$admin_role = new stdClass();
$admin_role->name = 'administrator';
...
user_role_save($admin_role);
user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));
This example shows that you can create a new user role, then access its rid
property, which was filled in by user_role_save()
. It also shows how to add permissions to that role with user_role_grant_permissions()
. In this case, it's granting the 'administrator' role all available permissions.
If you need to get the id of a user role created by someone else, you can use user_role_load_by_name()
to get the object for that user role. Then you just grab the id with $role->rid
.