Ansible Playbook to install NodeJS 24.x on Ubuntu

---
- name: Install NodeJS 24.x
  hosts: all
  become: true
  vars:
    node_major_version: 24
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes

    - name: Install prerequisites
      apt:
        name:
          - ca-certificates
          - curl
          - gnupg
        state: present

    - name: Create keyrings directory
      file:
        path: /etc/apt/keyrings
        state: directory
        mode: '0755'

    - name: Add NodeSource GPG key
      shell: |
        curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
      args:
        creates: /etc/apt/keyrings/nodesource.gpg

    - name: Add NodeSource repository
      shell: |
        echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_{{ node_major_version }}.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
      args:
        creates: /etc/apt/sources.list.d/nodesource.list

    - name: Update apt cache
      apt:
        update_cache: yes

    - name: Install NodeJS
      apt:
        name: nodejs
        state: present