Use Ansible playbook to enable and disable root login

Viewed 2887

I am new to Ansible and I'm trying to write my first Ansible playbook to enable root login via ssh two remote ubuntu servers.

By default, ssh to the two remote ubuntu servers as root is disabled. In order to enable the root login via ssh, I normally do this

#ssh to server01 as an admin user
ssh admin@server01

#set PermitRootLogin yes 
sudo vim /etc/ssh/sshd_config

# Restart the SSH server
service sshd restart

Now I'd like to do this via Ansible playbook.

This is my playbook

---
 - hosts: all
   gather_facts: no

   tasks:
   - name: Enable Root Login
     lineinfile:
           dest: /etc/ssh/sshd_config
           regexp: '^PermitRootLogin'
           line: "PermitRootLogin yes"
           state: present
           backup: yes
     notify:
       - restart ssh

   handlers:
   - name: restart ssh
     service:
       name: sshd
       state: restarted

I run the playbook as the admin user which was created in these two remote servers

ansible-playbook enable-root-login.yml -u admin --ask-pass

Unfortunately, the playbook is failed due to the permission denied.

fatal: [server01]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "msg": "Could not make backup of /etc/ssh/sshd_config to /etc/ssh/sshd_config.2569989.2021-07-16@06:33:33~: [Errno 13] Permission denied: '/etc/ssh/sshd_config.2569989.2021-07-16@06:33:33~'"}

Can anyone please advise what is wrong with my playbook? Thanks

1 Answers

When you edit sshd_config file you use sudo then you need to specify to the task that it must be executed with other user. You have to set the keyword become: yes, by default the become_user will be root and the become_method will be sudo and you also could to specifiy the become_password.

---
 - hosts: all
   gather_facts: no

   tasks:
   - name: Enable Root Login
     lineinfile:
           dest: /etc/ssh/sshd_config
           regexp: '^PermitRootLogin'
           line: "PermitRootLogin yes"
           state: present
           backup: yes
     become: yes
     notify:
       - restart ssh

   handlers:
   - name: restart ssh
     systemctl:
       name: sshd
       state: restarted

Documentation: https://docs.ansible.com/ansible/latest/user_guide/become.html#using-become

Related