How to create sudoer in Centos 7 using Ansible

Ansible is a great automation, configuration and server orchestration tool. In this example we will develop a script in ansible to create a sudo user.

Prerequistes:

  • Centos 7 server

Step1: Specify the host servers and the user to access the server. Here, our user is the root user. Remember to begin your playbook with —


– hosts: test-servers
remote_user: root

Step 2: We’d like to validate that wheel group exists since sudoers must be in this group. Normally, this group should exist by default.

– name: Validate that ‘wheel’ group exists
group:
name: wheel
state: present

Step 3: Next, we may choose to allow passwordless sudo. This allows you to just append the word sudo before your commands as the given user and get your command running.

– name: Allow passwordless sudo in wheel group
lineinfile:
path: /etc/sudoers
state: present
regexp: ‘^wheel’
line: ‘%wheel ALL=(ALL) NOPASSWD: ALL’
validate: ‘visudo -cf %s’

Step 4: Add your user to the group. Here, we add a user called ansible and create a home directory for the user.

– name: Add sudoers user to wheel group
user: name=ansible groups=wheel append=yes state=present createhome=yes

Step 5: It’s normally easier and good to access a server using SSH keys. So, we go ahead and set up authkeys for our sudoer, ansible to access the server
– name: Setup authkeys for user ansible
authorized_key:
user: ansible
state: present
key: “{{ lookup(‘file’, ‘/home/wm/.ssh/id_rsa.pub’) }}”

 

Walah! That should create your new sudoer. To test, try accessing the server using SSH. Just typing a command in the format ssh -p xxxx [email protected] should work – replacing the prot number and the server IP as appropriate.

The full playbook should be as follows:


– hosts: test-servers
remote_user: root

tasks:

– name: Validate that ‘wheel’ group exists
group:
name: wheel
state: present

– name: Allow passwordless sudo in wheel group
lineinfile:
path: /etc/sudoers
state: present
regexp: ‘^wheel’
line: ‘%wheel ALL=(ALL) NOPASSWD: ALL’
validate: ‘visudo -cf %s’

– name: Add sudoers user to wheel group
user: name=ansible groups=wheel append=yes state=present createhome=yes

– name: Setup authkeys for user alpha
authorized_key:
user: ansible
state: present
key: “{{ lookup(‘file’, ‘/home/wm/.ssh/id_rsa.pub’) }}”

Leave a Reply

Your email address will not be published.