Tuesday, November 19, 2024

Setup A NTP Server TO sync the windows machines locally

 Hello Guys,

I have working on a problem where i need to sync the windows machines in isolated network.So I have suggested that we need to have a local NTP server and keep syncing to it periodically. I have wrote a ansible playbook to setup NTP/chrony  server but it can be achive manually as well.

For syncing the windows machines as well we can do it locally but i have sestup a playbook which login on windows machine and syncup the time using the timeserver which we have setup.

---
- name: Set up NTP server on RHEL 9 using Chrony
hosts: all
become: yes
tasks:
- name: check if chrony is installed
shell: rpm -qa | grep chrony
register: chrony_installed
ignore_errors: True
check_mode: False
changed_when: False

- name: print
debug:
msg: "chrony is installed"
when: chrony_installed.rc == 0
- name: Install chrony package
yum:
name: chrony
state: present
when: chrony_installed.rc != 0

- name: Configure chrony as an NTP server
copy:
dest: /etc/chrony.conf
content: |
# Use the default CentOS pool servers
pool 2.centos.pool.ntp.org iburst

# Allow NTP client access from the local network
allow 192.168.1.0/24

#Allow NTP client to access from local network hostonly
allow 192.168.56.0/24

# Serve time even if not synchronized to any NTP server
local stratum 10

# Specify log file
logdir /var/log/chrony

# Dump measurements when chronyd exits
dumpdir /var/lib/chrony

# Save drift file
driftfile /var/lib/chrony/drift

notify:
- restart chronyd

- name: Enable and start chronyd service
systemd:
name: chronyd
enabled: yes
state: started

- name: Ensure firewalld is running
ansible.builtin.service:
name: firewalld
state: started
enabled: yes

- name: Open UDP port 123 for NTP (Chrony) on the server
ansible.posix.firewalld:
port: "{{ item }}/udp"
permanent: true
state: enabled
immediate: true
loop:
- 123
- 323
notify:
- Reload firewalld
handlers:
- name: restart chronyd
systemd:
name: chronyd
state: restarted

- name: Reload firewalld
ansible.builtin.service:
name: firewalld
state: reloaded


For syncing the we can go to time and date setting and  enter the IP address of the NTP server in the internet time section and click sync now. Alternatively we can also write a playbook if we want to do it in bulk which i will cover in the next article. Cheers and enjoy...!   




Friday, October 25, 2024

Check Validity of SSL certificate using notify if expiring in 30 days

 Hello Guys,

I was working on a use case where i need to write a playbook if the SSL cert is expiring in nexy 30 days.I should get a email alert that the ssl cert for the site will expire and reminding me to renew the same.

    So i have wrote a playbook and schedule to execute it every week So i keep on getting reminders that i need to renew the ssl cert. the playbook looks like this   

---
- name: check the certs for site
hosts: localhost
# connection: local
vars:
worn: 30
user_email: vijay9867206455@gmail.com
site_url: www.google.com
tasks:
- name: Get a cert from an https port
community.crypto.get_certificate:
host: "{{ site_url }}"
port: 443
delegate_to: localhost
register: cert

- name: How many days until cert expires
ansible.builtin.debug:
msg: "cert expires in: {{ expire_days }} days."
when: expire_days | int <= "{{ worn }}"| int
vars:
expire_days: "{{ (( cert.not_after | to_datetime('%Y%m%d%H%M%SZ')) - (ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%SZ')) ).days }}"
- name: Include Jinja template for email body
template:
src: alert_email.html.j2
dest: /tmp/alert_email.html
vars:
expire_days: "{{ (( cert.not_after | to_datetime('%Y%m%d%H%M%SZ')) - (ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%SZ')) ).days }}"
when: expire_days | int <= "{{ worn }}"| int

- name: Send email Alert
mail:
host: smtp.gmail.com
port: 587
subtype: html
to:
- "vijay9867206455@gmail.com"
subject: "Alert: cert is failing on"
subtype: html
body: "{{ lookup('file', '/tmp/alert_email.html') }}"
username:
password:
when: expire_days | int <= "{{ worn }}"
vars:
expire_days: "{{ (( cert.not_after | to_datetime('%Y%m%d%H%M%SZ')) - (ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%SZ')) ).days }}"
when: expire_days | int <= "{{ worn }}"| int

replace the email id with your own email id and also update the username and password for the email and you write a nice email template for it and that should be it.


Monday, September 30, 2024

Ansible Lockout User in WIndows

 Hello Guys,

As i have already told you i am recently extensively working with windows systems.I have come across one more use case where i need to lock the users after 3 unsuccessfully login attempt ans the user is local and not connected to Ad environment 


I have written the playbook which work without AD

---

- hosts: windows

  tasks:

- name: Set user lockout after 3 attempt 

  win_command: net accounts /lockoutthreshold:3

  register: userLockout

  args:

    creates: C:\userLockout.lock


- name: Create userLockout.lock 

  win_copy:

    dest: C:\userLockout.lock

    content: ""

    force: no

  when: userLockout


- name: Set lockout duration to 10 min  

  win_command: net accounts /lockoutduration:10

  register: lockduration

  args:

    creates: C:\lockduration.lock


- name: Create lockduration.lock 

  win_copy:

    dest: C:\lockduration.lock

    content: ""

    force: no

  when: lockduration


- name: Set reset the lockout timeout adter 

  win_command: net accounts /lockoutwindow:10

  register: lockoutwindow

  args:

    creates: C:\lockoutwindow.lock


- name: Create lockoutwindow.lock 

  win_copy:

    dest: C:\lockoutwindow.lock

    content: ""

    force: no

  Enjoy ..! Let me know if you stuck with Automation with Ansible

Ansible To setup Banner on Windows Host

 Hello Guys,

I am recently working on a project where I am working mostly on windows system, I got a requirement where i need to setup a banner on a windows machines. I did some google for manual steps as i don't have much understanding of windows but i was able to get the required steps

its basically i need to make some registry entries and that should take care of it

so i have started writing playbook.You can use this playbook and modify as you see feet for your use case

---

- name: Set Windows Login Banner

  hosts: all

  vars:

    title: "Company Name Authorised Access Only..!"

    body: ""This is a secure system of Company Name. Unauthorised access is prohibited.This system is under the surveillance and any authorised access will be reported. Powered by Ansible Automation  and Written by Navneet N. Rathi.""


  tasks:

    - name: Set banner caption (title) for Windows

      ansible.windows.win_regedit:

        path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

        name: LegalNoticeCaption

        data: "{{ title }}"

        type: String

      register: title


    - name: Set banner text (body) for Windows

      ansible.windows.win_regedit:

        path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

        name: LegalNoticeText

        data: "{{ body }}"

        type: String

      register: content


    - name: Reboot the machine

      ansible.windows.win_reboot:

        reboot_timeout: 120

      when: title.changed or content.changed

      ignore_errors : true


- hosts: all

  tasks:

   - name: check if win server is up or not

     ansible.builtin.win_ping:

     register: ping_status


   - name: Display the status

     ansible.builtin.debug:

       msg: "{{ ping_status }}"   


You can use this play to set it up..!

Enjoy..! Let me know if you have any automation use case for which you need help..!


Friday, August 16, 2024

Enable and Disable USB support on Linux servers without reboot

 Hello Guys,

In past couple of weeks i was working on a small project with very specific objective where i need to enable and disable the usb support on linux based edge device. I have use raspberry pi 4 as i don't have any  other supported industrial controller with me.

I have started with installing the default available os on the rasberry pi and i was able to login on the system which looks like 


after doing it i need to enable and disable the usb support on lets say hundreds of devices so its automation is the way cant do it manually at the same time i need to make sure that system should not required reboot other wise it will beat the purpose. so i can not go with conventional way of disabling the usb support at kernel level.

so after much google i have come across a utility in linux called usbguard which can be helpful. once the approach is finalised then i have moved into the  write a playbook the playbook looks as 


---

- name: enable disable USB

  hosts: "{{target}}"

  become: true

  vars:

    enable_usb: allow


  tasks:

    - name: Install usb guard on redhat family os

      ansible.builtin.yum:

        name: usbguard

        state: present

      when: ansible_facts['os_family'] == 'RedHat'


    - name: Install usb guard on others

      ansible.builtin.apt:

        name: usbguard

        state: present

      when: ansible_facts['os_family'] == 'Debian'


    - name: Install usb guard on the edge devices

      ansible.builtin.template:

        src: usbguard-daemon.conf.j2

        dest:  /etc/usbguard/usbguard-daemon.conf

        owner: root

        group: root

        mode: '0600'


    - name: restart usb guard service to {{ enable_usb }}

      ansible.builtin.service:

        name: usbguard

        state: restarted

        enabled: true

and template look like 

RuleFile=/etc/usbguard/rules.conf


RuleFolder=/etc/usbguard/rules.d/


ImplicitPolicyTarget={{ enable_usb }}


PresentDevicePolicy={{ enable_usb}}


PresentControllerPolicy={{enable_usb}}


InsertedDevicePolicy=apply-policy



RestoreControllerDeviceState=false


DeviceManagerBackend=uevent



IPCAllowedUsers=root


IPCAllowedGroups=wheel


IPCAccessControlFiles=/etc/usbguard/IPCAccessControl.d/


DeviceRulesWithPort=false


AuditBackend=FileAudit


AuditFilePath=/var/log/usbguard/usbguard-audit.log



using above automation i can enable and disable the usb support with the redhat aap with a one click


with This one job i can get my job done