How to assign permissions to roles programmatically? I have some permissions that I would like to assign to some roles programmatically for easier installation.

Because I'm installing the module and creating both permission and roles, I don't have the role id's, where I want to set the permissions. So far I have only found ways to assign roles programmatically that need the role ID.

I wonder if I somehow could look up the roles with their name (string), retrieve the role ID and then assign permission. It just doesn't feel right.
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-&gt;name = 'administrator';
...
user_role_save($admin_role);
user_role_grant_permissions($admin_role-&gt;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-&gt;rid.