Allow root access without password

First add a user:

$ sudo adduser ubuntu
$ sudo usermod -aG sudo ubuntu

Edit sudoser file with visudo (edit the sudoers file in a safe fashion).

$ sudo visudo

Add this line in the last line and save it.


Now sudo -s or sudo su - will login to root without asking password. This is also
required if you want to run ansible scripts with become: yes
(see: ansible docs).

Next thing we need to add our ssh public key to .ssh/authorized_keys so that we can
ssh without password.

$ cd  # go to home directory
$ mkdir .ssh
$ chmod 755 ~/.ssh  # .ssh directory should have 755 permissions and be owned by the user
$ touch authorized_keys
$ chmod 644 ~/.ssh/authorized_keys  # authorized_keys file should have 644 permissions and be owned by the user
$ nano .ssh/authorized_keys

Copy and paste your public ssh key into .ssh/authorized_keys and save it. That is it.

You can also run this ansible playbook to do basically the same thing:

- hosts: all
    - name: Add the user 'ubuntu' with a primary group of 'admin'
        name: ubuntu
        groups: admin
        append: yes
    - name: PKI | get pubkey from Github and placed as authorized_keys
       url:{{ item }}.keys
       dest: /tmp/{{ item }}.keys
        - karantan
    - name: PKI | Ensure .ssh/ folder exists
        owner: ubuntu
        group: ubuntu
        path: /home/ubuntu/.ssh/
        state: directory

    - name: PKI | Add downloaded keys to authorized_keys
        dest: /home/ubuntu/.ssh/authorized_keys
        src: /tmp
        regexp: \.keys$
        owner: ubuntu
        group: ubuntu

    - name: PKI | Disallow password authentication
        dest: /etc/ssh/sshd_config
        regexp: "^(#)?(\\s)?PasswordAuthentication (yes|no)$"
        line: PasswordAuthentication no

    - name: Restart sshd
      action: service name=ssh state=restarted

And then you can run playbooks as ubuntu like this:

- hosts: <hosts>
    - name: Create test directory as ubuntu user
      become: yes
      become_user: ubuntu
        path: /home/ubuntu/test
        state: directory

    - name: Create test2 directory as root
        path: /home/ubuntu/test2
        state: directory

Leave a Reply

Your email address will not be published.