How do I grant to roles dynamically created permissions?
After granting the permissions, you should call the save() method to make the code work.

if ($anonymous_role = Role::load($anonymous_rid)) {
  $anonymous_role-&gt;grantPermission($permission);
  $anonymous_role-&gt;save();
}