Repository: ansible-collections/community.general

Issue:
pkgng reports insufficient privilege as ok/unchanged, inconsistent with builtin.apt, builtin.yum
### Summary

With a barebones "update all installed packages" playbook, a server that requires sudo/root privileges to do so, and intentionally not providing said credentials, pkng reports green/ok/unchanged although it fails to do the task. This is inconsistent with builtin.apt and builtin.yum modules that correctly report red/failed with a result msg of "You need to be root" and "Are you root?" respectively.

### Issue Type

Bug Report

### Component Name

pkgng

### Ansible Version

```console (paste below)
$ ansible --version

ansible [core 2.13.4]
  config file = None
  configured module search path = ['/Users/alexis/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/Cellar/ansible/6.4.0/libexec/lib/python3.10/site-packages/ansible
  ansible collection location = /Users/alexis/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/local/bin/ansible
  python version = 3.10.7 (main, Sep 15 2022, 01:51:29) [Clang 14.0.0 (clang-1400.0.29.102)]
  jinja version = 3.1.2
  libyaml = True
```


### Community.general Version

```console (paste below)
$ ansible-galaxy collection list community.general

# /usr/local/Cellar/ansible/6.4.0/libexec/lib/python3.10/site-packages/ansible_collections
Collection        Version
----------------- -------
community.general 5.6.0  
```


### Configuration

```console (paste below)
$ ansible-config dump --only-changed

(empty)
```


### OS / Environment

Control node: macOS Monterey 12.6
Managed (target) node: FreeBSD 13.1-RELEASE amd64

### Steps to Reproduce

<!--- Paste example playbooks or commands between quotes below -->
My playbook:
```yaml (paste below)

---
- name: ensures server is up to date
  hosts: freebsd-server

  tasks:
  - name: upgrade all packages
    pkgng:
      name: '*'
      state: latest
```

Command to run playbook:
```console
$ ansible-playbook -i inventory.ini freebsd-update.yml -vvv
```

### Expected Results

pkgng should return red/failed when it attempts to do a task it has insufficient privileges for to be consistent with builtin.apt and builtin.yum. 

As an example, here's the -vvv update from a different server running apt:
```console

fatal: [debian]: FAILED! => {
    "changed": false,
    "invocation": {
        "module_args": {
            "allow_change_held_packages": false,
            "allow_downgrade": false,
            "allow_unauthenticated": false,
            "autoclean": false,
            "autoremove": false,
            "cache_valid_time": 0,
            "clean": false,
            "deb": null,
            "default_release": null,
            "dpkg_options": "force-confdef,force-confold",
            "fail_on_autoremove": false,
            "force": false,
            "force_apt_get": false,
            "install_recommends": null,
            "lock_timeout": 60,
            "name": "*",
            "only_upgrade": false,
            "package": [
                "*"
            ],
            "policy_rc_d": null,
            "purge": false,
            "state": "latest",
            "update_cache": null,
            "update_cache_retries": 5,
            "update_cache_retry_max_delay": 12,
            "upgrade": null
        }
    },
    "msg": "'/usr/bin/apt-get upgrade --with-new-pkgs ' failed: E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)\nE: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?\n",
    "rc": 100,
    "stdout": "",
    "stdout_lines": []
}
```

### Actual Results

The verbose result as printed in the terminal:
```console (paste below)

ok: [freebsd-server] => {
    "changed": false,
    "invocation": {
        "module_args": {
            "annotation": null,
            "autoremove": false,
            "cached": false,
            "chroot": null,
            "ignore_osver": false,
            "jail": null,
            "name": [
                "*"
            ],
            "pkgsite": null,
            "rootdir": null,
            "state": "latest"
        }
    },
    "msg": "no packages need upgrades",
    "stderr": "pkg: Insufficient privilege to upgrade packages\n",
    "stderr_lines": [
        "pkg: Insufficient privilege to upgrade packages"
    ],
    "stdout": "",
    "stdout_lines": []
}
```

Result of pkg update if I run it without privileges directly on the target server:
```console
user@freebsd-server:~ $ pkg update
pkg: Insufficient privileges to update the repository catalogue.
```

### Code of Conduct

- [X] I agree to follow the Ansible Code of Conduct


Discussion:
Files identified in the description:
* [`plugins/modules/packaging/os/pkgng.py`](https://github.com/ansible-collections/community.general/blob/main/plugins/modules/packaging/os/pkgng.py)

If these files are incorrect, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/devel/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @JoergFiedler @MacLemon @bcoca @dch @jasperla @mekanix @opoplawski @overhacked @tuxillo
[click here for bot help](https://github.com/ansible/ansibullbot/blob/devel/ISSUE_HELP.md)
<!--- boilerplate: notify --->
It looks to me that the module isn't checking return codes most of the time, when it really should.

Resolving patch:
diff --git a/plugins/modules/packaging/os/pkgng.py b/plugins/modules/packaging/os/pkgng.py
--- a/plugins/modules/packaging/os/pkgng.py
+++ b/plugins/modules/packaging/os/pkgng.py
@@ -37,7 +37,7 @@
     state:
         description:
             - State of the package.
-            - 'Note: "latest" added in 2.7'
+            - 'Note: C(latest) added in 2.7.'
         choices: [ 'present', 'latest', 'absent' ]
         required: false
         default: present
@@ -148,10 +148,7 @@ def query_package(module, run_pkgng, name):
 
     rc, out, err = run_pkgng('info', '-g', '-e', name)
 
-    if rc == 0:
-        return True
-
-    return False
+    return rc == 0
 
 
 def query_update(module, run_pkgng, name):
@@ -161,10 +158,7 @@ def query_update(module, run_pkgng, name):
     # rc = 1, updates available
     rc, out, err = run_pkgng('upgrade', '-g', '-n', name)
 
-    if rc == 1:
-        return True
-
-    return False
+    return rc == 1
 
 
 def pkgng_older_than(module, pkgng_path, compare_version):
@@ -190,7 +184,7 @@ def upgrade_packages(module, run_pkgng):
 
     pkgng_args = ['upgrade']
     pkgng_args.append('-n' if module.check_mode else '-y')
-    rc, out, err = run_pkgng(*pkgng_args)
+    rc, out, err = run_pkgng(*pkgng_args, check_rc=(not module.check_mode))
 
     matches = re.findall('^Number of packages to be (?:upgraded|reinstalled): ([0-9]+)', out, re.MULTILINE)
     for match in matches:


Test patch:
diff --git a/tests/integration/targets/pkgng/tasks/freebsd.yml b/tests/integration/targets/pkgng/tasks/freebsd.yml
--- a/tests/integration/targets/pkgng/tasks/freebsd.yml
+++ b/tests/integration/targets/pkgng/tasks/freebsd.yml
@@ -136,6 +136,42 @@
           - pkgng_example4.changed
           - not pkgng_example4_idempotent.changed
 
+##
+## pkgng - example - state=latest for out-of-date package without privileges
+##
+- name: Install intentionally out-of-date package and try to upgrade it with unprivileged user
+  block:
+    - ansible.builtin.user:
+        name: powerless
+        shell: /bin/bash
+
+    - name: Create out-of-date test package
+      import_tasks: create-outofdate-pkg.yml
+
+    - name: Install out-of-date test package
+      command: 'pkg add {{ pkgng_test_outofdate_pkg_path }}'
+      register: pkgng_example4_nopower_prepare
+
+    - name: Check for any available package upgrades with unprivileged user
+      become: true
+      become_user: powerless
+      pkgng:
+        name: '*'
+        state: latest
+      register: pkgng_example4_nopower_wildcard
+      ignore_errors: true
+
+    - name: Remove test out-of-date package
+      pkgng:
+        name: '{{ pkgng_test_pkg_name }}'
+        state: absent
+
+    - name: Ensure pkgng upgrades package correctly
+      assert:
+        that:
+          - not pkgng_example4_nopower_prepare.failed
+          - pkgng_example4_nopower_wildcard.failed
+
 ##
 ## pkgng - example - Install multiple packages in one command
 ##