Ansible, Windows and PowerShell: the Basics – Part 10, Local Users

In Part 10 of this series we’ll continue our journey with Ansible, Windows and PowerShell and look at how to handle local Windows user accounts. Hopefully, most of the time you are able to use AD based accounts and Group Policy to configure local access. However, sometimes there can be a need to manage and maintain local credentials.

In this example we will look at how to create a local user account and (sometimes more importantly) how to ensure a local account does not exist.

On our test server the local accounts are currently configured as below:

The following example will demonstrate how to use the win_user module to create a new user account test_user01 and secondly how to make sure the account test_user02 in the above screenshot does not exist .

However, before that, we’ll take a slight digression to talk about credentials. The example for the win_user module has the password for the new user account hard-coded into the playbook. This is obviously not a good practice both from a manageability and security point of view:

Instead, the credentials for this account should ideally arrive from an external and secure source. Hopefully your organisation uses some kind of password management system such as CyberArk or Hashicorp Vault where it would be possible to programmatically retrieve the credentials as part of the playbook.

Another basic option, which is useful when in a small test environment, is to use the Credentials feature built into AWX. There are a number of built-in credential types for use with different systems, but in this example we will create a custom credential type for Local Accounts - a good explanation exists here on how to do that.

Within Credential Types in the AWX console we define our Local_Account type:

Note that when defining local_account_password we set secret to be true, this ensures the value is not inadvertently displayed in any log.

Now we can create a new AWX credential of the Local _Account type to store the elements we need to create a local Windows account:

Our job template in AWX is _9_local_users. Note that as well as attaching an admin credential to the template as normal in order to connect to the machine to configure, we also attach the Local_Account credential above which we will reference subsequently in the playbook:

The contents of _9_local_users.yml are as follows:

Observe no hard-coded password to create the local account, rather we are able to reference the info supplied via extra_vars of the attached Local_Account credential, i.e. local_account_username, local_account_fullname and local_account_password.

In the second part of the playbook we simply state the name of the local account we do not wish to exist and set it’s state to absent.

Running a job from the _9_local_users job template produces the following result:

In the local users management tool, test_user01 has been created and test_user02 removed: