Block USB Stroage Devices Using Ansible Playbook

Disable USB Using Ansible Playbook on Linux Servers.

Today, In this article I will explains how to block USB storage devices using ansible playbook.

1) Setting up inventory file for remote hosts.

For the inventory, I created a file hosts and filled it with following content details.

/etc/ansible# cat hosts
server1 ansible_host=172.16.1.2 ansible_user=gaurav ansible_ssh_pass=123 ansible_connection=ssh

2) Setting up playbook.

In second step I created the playbook (i.e playbook.yaml) and add hosts (ansible run this playbook for server1 server)
I set ‘become’ to true to activate privilege escalation and use ‘become_method’ as a sudo (In our case ‘gaurav’ is the sudo user).

-
  name: 'Playbook for Block USB in linux Servers'
  hosts: server1
  become: True
  become_method: sudo
  tasks:
    - name: 'Find kernal version on remote systems'
      register: unameout
      command: "uname -r"
    - debug:
        var: unameout.stdout
    - name: 'Find usb-stroage.io file; if it is exist then next step will perform..'
      stat:
        path: /lib/modules/{{ unameout.stdout }}/kernel/drivers/usb/storage/usb-storage.ko
      register: stat_result
    - name: 'USB Blocked (if usb-stroage.io file not exist then this step will skipped)'
      command: mv /lib/modules/{{ unameout.stdout }}/kernel/drivers/usb/storage/usb-storage.ko  /lib/modules/{{ unameout.stdout }}/kernel/drivers/usb/storage/usb-storage.ko.bak
      when: stat_result.stat.exists == True
    - name: 'Reboot Server after Renaming usb-storage.ko file'
      reboot:

In this playbook, I can first check that the destination file exists or not and then make a decision based on the output of its result.

3) Execute the playbook.

Execute the playbook in ansible server using below command.

root@ansible:/etc/ansible/playbook# ansible-playbook playbook.yaml --ask-become-pass

Ansible will then print the feedback for each task.

The USB file has renamed of my remote servers you can see the output above screenshot for remote server.

Hope this post will help Devops beginners. Please share you feedback and Comments. Stay tune for more updates with ittroubleshooter.in …!!!

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of