Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run Ansible with root user and then change to another?

I have my fresh Ubuntu server on Linode and I have a root password for that server.

Now my Ansible playbook is like this:

- hosts: linode
  sudo: true
  remote_user: user1
  roles:
     - role: common
     - role: apache2

I want to execute the playbook as user1, but thing is user1 does not exist yet and I don't want to run roles as root. I need to manually create user1 before running a playbook. Is there any way to automate that?

like image 461
Mirage Avatar asked Jun 02 '14 08:06

Mirage


People also ask

How do I switch to root in Ansible?

To run a specific command as the root user in Ansible, you can implement the become directive and set the value to 'true. ' Doing this tells Ansible to implement sudo with no arguments when running the command.

Should Ansible be run as root?

You need to be root to execute - ansible.

How do I run as sudo user Ansible?

Ansible Sudo or become is a method to run a particular task in a playbook with Special Privileges like root user or some other user. become and become_user both have to be used in a playbook in certain cases where you want your remote user to be non-root.it is more like doing sudo -u someuser before running a task.

How do I run Ansible in parallel?

If you want to run multiple tasks in a playbook concurrently, use async with poll set to 0. When you set poll: 0 , Ansible starts the task and immediately moves on to the next task without waiting for a result. Each async task runs until it either completes, fails or times out (runs longer than its async value).


2 Answers

Keep in mind that you are allowed multiple "plays" in a single playbook file. So this could be the contents of a single playbook file:

- name: First play, to create the user
  hosts: linode
  sudo: true
  remote_user: root

  tasks:
    -  name: create my user
       user: name=user1 password=etc... 

- Second play, to do the rest of the work
  hosts: linode
  sudo: false
  remote_user: user1
  roles:
     - role: common
     - role: apache2

Note that I have used a task to create the user, but that could be a role so you can re-use it between different projects.

like image 72
Ramon de la Fuente Avatar answered Sep 28 '22 09:09

Ramon de la Fuente


You can create a very simple bootstrap playbook that you run as root and it'll create your user1 which will then run all the other playbooks.

like image 37
Mxx Avatar answered Sep 28 '22 08:09

Mxx