Repository: ansible/ansible

Issue:
Patch module is unable to detect if a patch was already applied on OpenBSD
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### SUMMARY
<!--- Explain the problem briefly -->
The patch module is trying to apply a patch which was applied in a previous run of ansible on OpenBSD and the run fails. The reason for this is that the check which is determining if a patch was already applied is always true on OpenBSD. The check tries to run patch with --dry-run which does not exist. The option is called --check.

See OpenBSD manpage: https://man.openbsd.org/patch.1
According to the man page the issue exists also for NetBSD: http://netbsd.gw.com/cgi-bin/man-cgi?patch++NetBSD-current

##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
patch

##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.5.4
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/XXX/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.5 (default, May 11 2018, 04:00:52) [GCC 8.1.0]

```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->

##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->
Running ansbile from Arch Linux to manage OpenBSD 6.3

##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->

<!--- Paste example playbooks or commands between quotes below -->
On target OpenBSD machine:
Create file /tmp/somefile with the following contents
```
test 1
test 3

```

On the machine executing Ansible:
Create the following patch file and store it under files/somefile.patch
```
--- /tmp/somefile   Wed Jun 13 11:59:38 2018
+++ /tmp/somefile   Wed Jun 13 11:59:53 2018
@@ -1,2 +1,3 @@
 test 1
+test 2
 test 3

```

Create the playbook.yml with the following content:
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: all

  tasks:
  - name: Patching 
    patch:
      dest: "/tmp/somefile"
      src: files/somefile.patch
      backup: no
```

Execute the playbook with ansible-playbook playbook.yml which will patch the file sucessfully. Another run will fail because patch is executed again.

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
First run:
```
PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [default]

TASK [Patching] ****************************************************************
changed: [default]

PLAY RECAP *********************************************************************
default                    : ok=2    changed=1    unreachable=0    failed=0
```
Second run:
```
PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [default]

TASK [Patching] ****************************************************************
ok: [default]

PLAY RECAP *********************************************************************
default                    : ok=2    changed=0    unreachable=0    failed=0
```

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
First run:
```
PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [default]

TASK [Patching] ****************************************************************
changed: [default]

PLAY RECAP *********************************************************************
default                    : ok=2    changed=1    unreachable=0    failed=0
```

Second run:
```
PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [default]

TASK [Patching] ****************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was:  test 3
fatal: [default]: FAILED! => {"changed": false, "msg": "Ignoring previously applied (or reversed) patch.\n1 out of 1 hunks ignored--saving rejects to -\n@@ -1,2 +1,3 @@\n test 1\n+test 2\n test 3\n"}
	to retry, use: --limit @/tmp/playbook.retry

PLAY RECAP *********************************************************************
default                    : ok=1    changed=0    unreachable=0    failed=1
```



Discussion:
Files identified in the description:
* [lib/ansible/modules/files/patch.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/files/patch.py)

If these files are inaccurate, 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/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @jirutka @luisperlaz
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->

Resolving patch:
diff --git a/lib/ansible/modules/files/patch.py b/lib/ansible/modules/files/patch.py
--- a/lib/ansible/modules/files/patch.py
+++ b/lib/ansible/modules/files/patch.py
@@ -100,7 +100,7 @@
 
 import os
 from traceback import format_exc
-from ansible.module_utils.basic import AnsibleModule
+from ansible.module_utils.basic import AnsibleModule, get_platform
 from ansible.module_utils._text import to_native
 
 
@@ -108,10 +108,19 @@ class PatchError(Exception):
     pass
 
 
+def add_dry_run_option(opts):
+    # Older versions of FreeBSD, OpenBSD and NetBSD support the --check option only.
+    if get_platform().lower() in ['openbsd', 'netbsd', 'freebsd']:
+        opts.append('--check')
+    else:
+        opts.append('--dry-run')
+
+
 def is_already_applied(patch_func, patch_file, basedir, dest_file=None, binary=False, strip=0, state='present'):
-    opts = ['--quiet', '--forward', '--dry-run',
+    opts = ['--quiet', '--forward',
             "--strip=%s" % strip, "--directory='%s'" % basedir,
             "--input='%s'" % patch_file]
+    add_dry_run_option(opts)
     if binary:
         opts.append('--binary')
     if dest_file:
@@ -128,7 +137,7 @@ def apply_patch(patch_func, patch_file, basedir, dest_file=None, binary=False, s
             "--strip=%s" % strip, "--directory='%s'" % basedir,
             "--input='%s'" % patch_file]
     if dry_run:
-        opts.append('--dry-run')
+        add_dry_run_option(opts)
     if binary:
         opts.append('--binary')
     if dest_file:


Test patch: