Add user to OG based on roles? I am using drupal 7, I want to add users having role 'R' to a OG group 'G'.

Is it possible to do that?
Here's some code I've used, you can't add the role condition to EntityFieldQuery so the array needs to be filtered afterwards:

  $query = new EntityFieldQuery();
  $query-&gt;entityCondition('entity_type', 'user')
      -&gt;propertyCondition('uid', '1', '&gt;'); // skip the anonymous and admin
  $entities = $query-&gt;execute();
  $uids = array_keys($entities['user']);
  $accounts = user_load_multiple($uids);

  // filter the users array by role
  $include_roles = array('my_role', 'my_other_role');
  $filter = function ($value) use ($include_roles) {
        $isect = array_intersect($include_roles, $value-&gt;roles);
        return !empty($isect);
      };
  $accounts = array_filter($accounts, $filter);


Then, to add these to your group having id $gid

  foreach ($accounts as $account) {
    og_group($gid, array('entity' =&gt; $account, 'state' =&gt; OG_STATE_ACTIVE));
  }


Hope this helps. I think this should be doable in Rules, but I'm no expert in that.