Introduction
The community.general.npm module install, update, and manage Node.js packages globally or per-project with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use.
Quick Reference
- name: Basic npm usage
community.general.npm:
state: present
Parameters
| Parameter | Required | Default | Description |
|---|---|---|---|
state | No | present | Desired state (present/absent) |
name | Yes | — | Target resource name |
Installation
# Install the collection
ansible-galaxy collection install community.general
# Verify installation
ansible-doc community.general.npm
Basic Example
---
- name: Manage Node.js Packages with npm
hosts: all
become: true
tasks:
- name: Ensure resource is configured
community.general.npm:
name: example
state: present
Advanced Examples
Idempotent Configuration
- name: Configure with all options
community.general.npm:
name: production
state: present
register: result
- name: Show result
ansible.builtin.debug:
var: result
Conditional Execution
- name: Only on specific OS
community.general.npm:
name: example
state: present
when: ansible_os_family == "Debian"
Loop Over Multiple Items
- name: Configure multiple resources
community.general.npm:
name: "{{ item }}"
state: present
loop:
- resource1
- resource2
- resource3
Error Handling
- name: Handle failures gracefully
block:
- name: Attempt configuration
community.general.npm:
name: example
state: present
rescue:
- name: Log failure
ansible.builtin.debug:
msg: "Failed to configure npm: {{ ansible_failed_result.msg }}"
Troubleshooting
| Error | Cause | Fix |
|---|---|---|
| Module not found | Collection not installed | ansible-galaxy collection install community.general |
| Permission denied | Insufficient privileges | Add become: true |
| Timeout | Network/resource unavailable | Increase timeout, check connectivity |
| Idempotency issue | Module reports changed every run | Check parameter values match desired state |
Best Practices
- Use FQCN — always use
community.general.npminstead of short name - Register results — capture output for conditional logic
- Handle errors — use
block/rescuefor graceful failure handling - Test in check mode — run with
--checkbefore applying - Pin collection version — specify version in
requirements.yml
Related Modules
ansible.builtin.debug— Display variable valuesansible.builtin.assert— Validate conditionsansible.builtin.set_fact— Set variables from task results
Conclusion
The community.general.npm module provides idempotent install, update, and manage Node.js packages globally or per-project with Ansible Always use the FQCN, handle errors with block/rescue, and test with --check mode before production deployment.