Reputation: 33442
I need to provision a very fresh Ubuntu server with Ansible. At the beginning it only has root
user and a generated password. The first action I need to do is to create a service
user, set password to it, optionally, upload my local user's keys (so I will be able to log in without passwords) and disable root
logins. Then I need to run a role as a service
user. How can I do that in one playbook (e.g. signle ansible-playbook provision.yml
instead of ansible-playbook init.yml && ansible-playbook apply_roles.yml
)? The problem is that I need to switch users somewhere after I created service
and then (and all future logins) I need to login as him.
Is it a good idea to configure ansible_user
for this host as service
and only override it once (to root
) for initial setup? Any best practices?
Upvotes: 1
Views: 288
Reputation: 888
If memory serves, a Ubuntu instance starts out with a generated root user and a local user with access to sudo:
I think the cleanest approach to this would be to install that local user's keys via bash script first, via:
ssh-copy-id <server>
( if that command is available from the command line where you run ansible )
and then go on to run your Ansible script after that line in the bash script.
( Though I think it would also possible to store the creds of the local user in an ansible vault .. I haven't used the vault yet, so I'm less familiar with it. )
I would specify the service user in either a kick-off file ( as become_user ) or via ansible_user in the inventory, as you said. ( But you may run into issues with doing that according to this older issue. )
If I used a kick-off file to specify the user, that file would have a role ( let's say web-server ), and that role would have a dependency ( let's say common ).
In the common role, I would have a task that attempted a command with a known result using the service user ( that was set to ignore errors ). If that task didn't return the expected result, I would then create the service user and copy that service user's keys to the server. Each task involved would need to override the become_user to the local user.
After that role dependency was executed, the main role(s) would follow, and all of the remaining tasks should be executed as the service user.
Upvotes: 1
Reputation: 11
You can have multiple plays in a single playbook. Create a play for the tasks you would like to run as root and another one for role that should run as service:
- hosts: all
remote_user: root
tasks:
# your tasks here
- hosts: all
remote_user: service
roles:
- your_role
Upvotes: 1