How can I programmatically create an api role (SOAP)

I ended up doing something like the following in my data-install-1.0.0.php script, which creates a new role and user with 'all' privileges.

$api_key = "your_key_here";

$api_role = Mage::getModel('api/roles')
        ->setName('<module>')
        ->setPid(false)
        ->setRoleType('G')
        ->save();

Mage::getModel('api/rules')
        ->setRoleId($api_role->getId())
        ->setResources(array('all'))
        ->saveRel();

$api_user = Mage::getModel('api/user');

$api_user->setData(array(
        'username' => '<module>',
        'firstname' => '<module>',
        'lastname' => '<module>',
        'email' => 'support@<module>.com',
        'api_key' => $api_key,
        'api_key_confirmation' => $api_key,
        'is_active' => 1,
        'user_roles' => '',
        'assigned_user_role' => '',
        'role_name' => '',
        'roles' => array($api_role->getId())
          ));

$api_user->save()->load($api_user->getId());

$api_user->setRoleIds(array($api_role->getId()))
        ->setRoleUserId($api_user->getUserId())
        ->saveRelations();

Of course this is simplified, you would likely want to include some error handling.

UPDATE: If you're following along you may run into an issue with the above code not saving your api key. If so try the following:

$salt = ('somekindofsalthere');

$api_key = md5($salt.'somekindOfPasswordHere02').':'.$salt;

Now, rather than using $api_user->setData() with api_key and api_key_confirmation, we're going to set the api key this way (notice the above 2 parameters have been removed and replaced with a new method below):

$user->setData(array(
            'username' => '<module>',
            'firstname' => '<module>',
            'lastname' => '<module>',
            'email' => 'support@<module>.com',
            'is_active' => 1,
            'user_roles' => '',
            'assigned_user_role' => '',
            'role_name' => '',
            'roles' => array($role->getId())
        ));
$user->setApiKey($api_key);

This should save your key to your newly created api user. Keep in mind the api key will not display on the backend, as those fields are for updating to a new key, and will not display the current key.