internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: ansible/ansible

Issue:
systemd module: should not check initscript status when user=yes
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
systemd module

##### ANSIBLE VERSION
ansible 2.2.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides

##### OS / ENVIRONMENT
Debian Jessie

##### SUMMARY
When setting enabled=yes or enabled=no, the systemd module, in order to check if an update is required, also check the status of legacy initscripts unit:

```
            initscript = '/etc/init.d/' + unit
            if os.path.exists(initscript) and os.access(initscript, os.X_OK) and \
               (not out.startswith('disabled') or bool(glob.glob('/etc/rc?.d/S??' + unit))):
                enabled = True
```

This prevent any user unit having the same name than an enabled system unit to be enabled (it will be considered as enabled even if it is not, and ansible will do nothing and report the task as unchanged).

##### STEPS TO REPRODUCE

1. Install and enable nginx, system-wide (after this there will be /etc/rc2.d/S02nginx  /etc/rc3.d/S02nginx  /etc/rc4.d/S02nginx  /etc/rc5.d/S02nginx files present in the system, at least under Debian)

2. Create a nginx user unit (in /etc/systemd/user/nginx.service): 

```
[Unit]
Description=A high performance web server and a reverse proxy server
After=network.target

[Service]
Type=simple
ExecStartPre=/bin/sh -c "exec /usr/sbin/nginx -c $$HOME/conf/nginx/nginx.conf -t -q"
ExecStart=/bin/sh -c "exec /usr/sbin/nginx -c $$HOME/conf/nginx/nginx.conf"
ExecReload=/bin/sh -c "exec /usr/sbin/nginx -c $$HOME/conf/nginx/nginx.conf -s reload"

[Install]
WantedBy=default.target
```

3. Check that the user unit is not enabled : `systemctl --user is-enabled nginx` should return `disabled`

4. Try to enable the user unit using ansible : `ansible 'localhost' -u $USER -m systemd -a "user=yes enabled=yes name=nginx"`

##### EXPECTED RESULTS

Expected result is to have ansible report a change, and `systemctl --user is-enabled nginx` to return `enabled`

##### ACTUAL RESULTS

ansible report unchaned, and the user unit is still disabled (`systemctl --user is-enabled nginx` still returns `disabled`)


Discussion:

Resolving patch:
diff --git a/lib/ansible/modules/system/systemd.py b/lib/ansible/modules/system/systemd.py
--- a/lib/ansible/modules/system/systemd.py
+++ b/lib/ansible/modules/system/systemd.py
@@ -359,8 +359,11 @@ def main():
         if rc == 0:
             enabled = True
         elif rc == 1:
-            # if both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries
-            if is_initd and (not out.startswith('disabled') or sysv_is_enabled(unit)):
+            # if not a user service and both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries
+            if not module.params['user'] and \
+               is_initd and \
+               (not out.strip().endswith('disabled') or sysv_is_enabled(unit)):
+
                 enabled = True
 
         # default to current state


Test patch:
Repository: ansible/ansible

Issue:
Documentation Error in http://docs.ansible.com/ansible/ldap_attr_module.html#ldap-attr


##### ISSUE TYPE
 - Documentation Report

##### COMPONENT NAME
ldap-attr ( New in version 2.3. )

##### ANSIBLE VERSION
```
ansible 2.3.0
  config file = 
  configured module search path = Default w/o overrides
```

##### CONFIGURATION


##### OS / ENVIRONMENT


##### SUMMARY
look like 2 Exemples are wrong: 
http://docs.ansible.com/ansible/ldap_attr_module.html#id4
We are in the module ldap_attr the last 2 exemples are about  ldap_entry (with attribut only exist in  ldap_attr )
- name: Get rid of an unneeded attribute
  ldap_entry:

- name: Get rid of an unneeded attribute
  ldap_entry:

##### STEPS TO REPRODUCE


##### EXPECTED RESULTS


##### ACTUAL RESULTS



Discussion:
cc @risaacson
[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/network/ldap_attr.py b/lib/ansible/modules/network/ldap_attr.py
--- a/lib/ansible/modules/network/ldap_attr.py
+++ b/lib/ansible/modules/network/ldap_attr.py
@@ -166,7 +166,7 @@
     olcRootPW: "{SSHA}tabyipcHzhwESzRaGA7oQ/SDoBZQOGND"
 
 - name: Get rid of an unneeded attribute
-  ldap_entry:
+  ldap_attr:
     dn: uid=jdoe,ou=people,dc=example,dc=com
     name: shadowExpire
     value: ""
@@ -184,7 +184,7 @@
 #   bind_dn: cn=admin,dc=example,dc=com
 #   bind_pw: password
 - name: Get rid of an unneeded attribute
-  ldap_entry:
+  ldap_attr:
     dn: uid=jdoe,ou=people,dc=example,dc=com
     name: shadowExpire
     value: ""


Test patch:
Repository: ansible/ansible

Issue:
lxc_container.py still uses lxc-clone for clones (it ought to use lxc-copy)
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
`lxc_container` module

##### ANSIBLE VERSION
```
ansible 2.2.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```

##### CONFIGURATION
No changes from package defaults.

##### OS / ENVIRONMENT
Ubuntu 16.04.1 LTS

##### SUMMARY
The module makes use of the `lxc-clone` command, which is deprecated in favor of `lxc-copy`, and will be removed in some future LXC release — in which case, if the module remains unchanged, clones will stop working.

##### EXPECTED RESULTS
`lxc_container.py` should invoke `lxc-copy` when creating clones.

##### ACTUAL RESULTS
`lxc_container.py` invokes `lxc-clone` when creating clones.



Discussion:
Tagging @cloudnull as the original author of `lxc_container.py`.
Sorry, accidentally hit "close and comment" instead of just "comment".
Evidently, *some* people are already being bitten by this because their distribution no longer ships `lxc-clone` (see ansible/ansible-modules-extras#2996).

Resolving patch:
diff --git a/lib/ansible/modules/cloud/lxc/lxc_container.py b/lib/ansible/modules/cloud/lxc/lxc_container.py
--- a/lib/ansible/modules/cloud/lxc/lxc_container.py
+++ b/lib/ansible/modules/cloud/lxc/lxc_container.py
@@ -477,7 +477,15 @@
         }
     },
     'clone': {
-        'variables': {
+        'variables-lxc-copy': {
+            'backing_store': '--backingstorage',
+            'lxc_path': '--lxcpath',
+            'fs_size': '--fssize',
+            'name': '--name',
+            'clone_name': '--newname'
+        },
+        # lxc-clone is deprecated in favor of lxc-copy
+        'variables-lxc-clone': {
             'backing_store': '--backingstore',
             'lxc_path': '--lxcpath',
             'fs_size': '--fssize',
@@ -792,13 +800,20 @@ def _container_create_clone(self):
             self.state_change = True
             self.container.stop()
 
+        # lxc-clone is deprecated in favor of lxc-copy
+        clone_vars = 'variables-lxc-copy'
+        clone_cmd = self.module.get_bin_path('lxc-copy')
+        if not clone_cmd:
+            clone_vars = 'variables-lxc-clone'
+            clone_cmd = self.module.get_bin_path('lxc-clone', True)
+
         build_command = [
-            self.module.get_bin_path('lxc-clone', True),
+            clone_cmd,
         ]
 
         build_command = self._add_variables(
             variables_dict=self._get_vars(
-                variables=LXC_COMMAND_MAP['clone']['variables']
+                variables=LXC_COMMAND_MAP['clone'][clone_vars]
             ),
             build_command=build_command
         )
@@ -814,7 +829,7 @@ def _container_create_clone(self):
 
         rc, return_data, err = self._run_command(build_command)
         if rc != 0:
-            message = "Failed executing lxc-clone."
+            message = "Failed executing %s." % os.path.basename(clone_cmd)
             self.failure(
                 err=err, rc=rc, msg=message, command=' '.join(
                     build_command


Test patch:
Repository: ansible/ansible

Issue:
gce_net error on firewall rule update: Unexpected response: ('ports')
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
gce_net

##### ANSIBLE VERSION
```
ansible 2.2.0.0
  config file = /home/rsimmons/work/clearcorrect/provisioning/ansible_env/devinfra/build/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```

##### CONFIGURATION
```
[defaults]
host_key_checking = False

[ssh_connection]
ssh_args = -F ./ssh.config -o ControlMaster=auto -o ControlPersist=30m -o StrictHostKeyChecking=no -o CheckHostIP=no
control_path = ~/.ssh/ansible-%%r@%%h:%%p
```

##### OS / ENVIRONMENT
N/A

##### SUMMARY
When updating an existing firewall rule an error occurs if the allowed list includes a protocol without a port, e.g. icmp.

##### STEPS TO REPRODUCE
1. Use gce_net to attempt to update an existing firewall rule in a GCE network.
2. Include a protocol without a port in the "allowed" attribute:
```
"allowed": "tcp:1-65535;udp:1-65535;icmp"
```

##### EXPECTED RESULTS
The firewall rule in GCE would either be updated or left unchanged if no update is necessary.

##### ACTUAL RESULTS
An error occurs in the `sorted_allowed_list` function:

```
   "msg": "Unexpected response: ('ports'). Detail: Traceback (most recent call last):\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 356, in main\n    if allowed_list and (sorted_allowed_list(allowed_list) != sorted_allowed_list(fw.allowed)):\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 234, in sorted_allowed_list\n    return sorted(allowed_by_protocol, key=lambda y: y['ports'].sort())\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 234, in <lambda>\n    return sorted(allowed_by_protocol, key=lambda y: y['ports'].sort())\nKeyError: 'ports'\n"
```



Discussion:
cc @supertom
[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/cloud/google/gce_net.py b/lib/ansible/modules/cloud/google/gce_net.py
--- a/lib/ansible/modules/cloud/google/gce_net.py
+++ b/lib/ansible/modules/cloud/google/gce_net.py
@@ -208,7 +208,7 @@ def format_allowed_section(allowed):
         return []
     if ports.count(","):
         ports = ports.split(",")
-    else:
+    elif ports:
         ports = [ports]
     return_val = {"IPProtocol": protocol}
     if ports:
@@ -231,7 +231,7 @@ def sorted_allowed_list(allowed_list):
     # sort by protocol
     allowed_by_protocol = sorted(allowed_list,key=lambda x: x['IPProtocol'])
     # sort the ports list
-    return sorted(allowed_by_protocol, key=lambda y: y['ports'].sort())
+    return sorted(allowed_by_protocol, key=lambda y: y.get('ports', []).sort())
 
 
 def main():


Test patch:
Repository: ansible/ansible

Issue:
apt_repository fails to enable a disabled apt repository
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
apt_repository

##### ANSIBLE VERSION
```
ansible 2.2.1.0
  config file = /home/mg/src/mg-infra/ansible.cfg
  configured module search path = Default w/o overrides
```

##### CONFIGURATION
n/a

##### OS / ENVIRONMENT
Ubuntu 16.04 LTS on the target; Ubuntu 16.10 on the controller

##### SUMMARY

`apt_repository: repo='ppa:pov' state=present` fails to re-enable the apt repository after it's been disabled by Ubuntu's `do-release-upgrade`

##### STEPS TO REPRODUCE

```yaml
- hosts: all
  tasks:
    # simulate adding a repository and then disabling it during do-release-upgrade
    - copy:
        content: "# deb http://ppa.launchpad.net/pov/ppa/ubuntu xenial main # disabled on upgrade to xenial\n"
        dest: /etc/apt/sources.list.d/ppa_pov_trusty.list
    - apt_repository: repo='ppa:pov' state=present
    - shell: grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/*.list
      register: repos
    - debug: var=repos.stdout_lines
```

##### EXPECTED RESULTS

I expect the repository to be re-enabled.

##### ACTUAL RESULTS

```
PLAY [ranka] *******************************************************************

TASK [copy] ********************************************************************
ok: [ranka]

TASK [apt_repository] **********************************************************
ok: [ranka]

TASK [command] *****************************************************************
changed: [ranka]

TASK [debug] *******************************************************************
ok: [ranka] => {
    "repos.stdout_lines": [
        "deb http://ports.ubuntu.com/ubuntu-ports xenial main universe", 
        "deb-src http://ports.ubuntu.com/ubuntu-ports xenial main universe", 
        "deb http://ports.ubuntu.com xenial-security main", 
        "deb http://ports.ubuntu.com xenial-security universe", 
        "deb http://ports.ubuntu.com xenial-updates main universe"
    ]
}

PLAY RECAP *********************************************************************
ranka                      : ok=4    changed=1    unreachable=0    failed=0   
```



Discussion:
Bug also present in current `devel` (32913c0fdf).



Resolving patch:
diff --git a/lib/ansible/modules/packaging/os/apt_repository.py b/lib/ansible/modules/packaging/os/apt_repository.py
--- a/lib/ansible/modules/packaging/os/apt_repository.py
+++ b/lib/ansible/modules/packaging/os/apt_repository.py
@@ -458,10 +458,11 @@ def repos_urls(self):
         _repositories = []
         for parsed_repos in self.files.values():
             for parsed_repo in parsed_repos:
-                enabled = parsed_repo[1]
+                valid = parsed_repo[1]
+                enabled = parsed_repo[2]
                 source_line = parsed_repo[3]
 
-                if not enabled:
+                if not valid or not enabled:
                     continue
 
                 if source_line.startswith('ppa:'):


Test patch:
Repository: ansible/ansible

Issue:
net_command on junos will fail if connecting as root
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
net_command
##### ANSIBLE VERSION
```
ansible 2.3.0 (devel 8fe09d4ea9) last updated 2017/01/11 08:23:39 (GMT +100)
  config file = 
  configured module search path = Default w/o overrides

```


##### SUMMARY
Junos devices have a root user that doesn't go straight into the `cli` shell

Initially this causes the detection code in `plugins/terminal/junos.py` to gracefully fail as `show version` returns an error.


```
root@ec2-54-204-196-139% show version
show: Command not found.
root@ec2-54-204-196-139% cli
show root@ec2-54-204-196-139> show version 
Hostname: ec2-54-204-196-139
Model: vsrx
Junos: 15.1X49-D60.7
JUNOS Software Release [15.1X49-D60.7]
```

##### STEPS TO REPRODUCE
Connect as root

##### EXPECTED RESULTS

##### ACTUAL RESULTS
```

```



Discussion:
Once fixed enable Junos `targets/net_command` in Shippable
@Qalthos I believe you look after Junos, could you please put in a fix for this. This will allow me to add basic Junos tests into Shippable

Resolving patch:
diff --git a/lib/ansible/plugins/terminal/junos.py b/lib/ansible/plugins/terminal/junos.py
--- a/lib/ansible/plugins/terminal/junos.py
+++ b/lib/ansible/plugins/terminal/junos.py
@@ -26,11 +26,17 @@
 from ansible.errors import AnsibleConnectionFailure
 
 
+try:
+    from __main__ import display
+except ImportError:
+    from ansible.utils.display import Display
+    display = Display()
+
 class TerminalModule(TerminalBase):
 
     terminal_prompts_re = [
         re.compile(r"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"),
-        re.compile(r"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"),
+        re.compile(r"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|%) ?$"),
     ]
 
     terminal_errors_re = [
@@ -40,6 +46,10 @@ class TerminalModule(TerminalBase):
 
     def on_open_shell(self):
         try:
+            prompt = self._get_prompt()
+            if prompt.strip().endswith('%'):
+                display.vvv('starting cli', self._connection._play_context.remote_addr)
+                self._exec_cli_command('cli')
             for c in ['set cli timestamp disable', 'set cli screen-length 0']:
                 self._exec_cli_command(c)
         except AnsibleConnectionFailure:


Test patch:
Repository: ansible/ansible

Issue:
Issues with string concat and implicit conversion of bytes to chars
in `ansible/inventory/script.py` there is code like:

```python
if not isinstance(self.raw, Mapping):
    sys.stderr.write(err + "\n")
    raise AnsibleError("failed to parse executable inventory script results from {0}: data needs to be formatted as a json dict".format(to_native(self.filename)))
```

I had to to change to this to get the actual error message (instead of the encoding error): `sys.stderr.write(err.decode('ascii') + "\n")`

I'm running python 3. 


Discussion:
Can you add information about how to reproduce the error message? Just running inventory scripts under Python 3? 
Yes, I'm working on an inventory script. The error message was the one above "data needs to be formatted as a json dict" but instead I was getting "Can't convert 'bytes' object to str implicitly" error
Also, I am running ansible 2.1, but the source in the master branch here (assuming that is 2.3) I assume has the same problem because it is not encoding the err object

Resolving patch:
diff --git a/lib/ansible/inventory/script.py b/lib/ansible/inventory/script.py
--- a/lib/ansible/inventory/script.py
+++ b/lib/ansible/inventory/script.py
@@ -77,11 +77,11 @@ def _parse(self, err):
         try:
             self.raw = self._loader.load(self.data)
         except Exception as e:
-            sys.stderr.write(err + "\n")
+            sys.stderr.write(to_native(err) + "\n")
             raise AnsibleError("failed to parse executable inventory script results from {0}: {1}".format(to_native(self.filename), to_native(e)))
 
         if not isinstance(self.raw, Mapping):
-            sys.stderr.write(err + "\n")
+            sys.stderr.write(to_native(err) + "\n")
             raise AnsibleError("failed to parse executable inventory script results from {0}: data needs to be formatted as a json dict".format(to_native(self.filename)))
 
         group = None


Test patch:
Repository: ansible/ansible

Issue:
urls.py py3-compatability (strings)
##### ISSUE TYPE
 - Bugfix Pull Request

##### COMPONENT NAME
`module_utils/urls.py`

##### ANSIBLE VERSION
<!--- Paste verbatim output from “ansible --version” between quotes below -->
```
2.3.0
```

##### SUMMARY
These comparisons were failing ("TypeError: a bytes-like object is required, not 'str'"). This should be py2/py3 compatible.




Discussion:
needs_info
related commit: 0ca3800ae106992e6a6c59f249959c47510cb675

I need to investigate.

Resolving patch:
diff --git a/lib/ansible/module_utils/urls.py b/lib/ansible/module_utils/urls.py
--- a/lib/ansible/module_utils/urls.py
+++ b/lib/ansible/module_utils/urls.py
@@ -115,7 +115,7 @@
 import ansible.module_utils.six.moves.urllib.error as urllib_error
 from ansible.module_utils.basic import get_distribution, get_exception
 from ansible.module_utils.six import b
-from ansible.module_utils._text import to_bytes, to_native
+from ansible.module_utils._text import to_bytes, to_native, to_text
 
 try:
     # python3
@@ -579,21 +579,21 @@ def get_ca_certs(self):
         ca_certs = []
         paths_checked = []
 
-        system = platform.system()
+        system = to_text(platform.system(), errors='surrogate_or_strict')
         # build a list of paths to check for .crt/.pem files
         # based on the platform type
         paths_checked.append('/etc/ssl/certs')
-        if system == 'Linux':
+        if system == u'Linux':
             paths_checked.append('/etc/pki/ca-trust/extracted/pem')
             paths_checked.append('/etc/pki/tls/certs')
             paths_checked.append('/usr/share/ca-certificates/cacert.org')
-        elif system == 'FreeBSD':
+        elif system == u'FreeBSD':
             paths_checked.append('/usr/local/share/certs')
-        elif system == 'OpenBSD':
+        elif system == u'OpenBSD':
             paths_checked.append('/etc/ssl')
-        elif system == 'NetBSD':
+        elif system == u'NetBSD':
             ca_certs.append('/etc/openssl/certs')
-        elif system == 'SunOS':
+        elif system == u'SunOS':
             paths_checked.append('/opt/local/etc/openssl/certs')
 
         # fall back to a user-deployed cert in a standard
@@ -605,7 +605,7 @@ def get_ca_certs(self):
         to_add = False
 
         # Write the dummy ca cert if we are running on Mac OS X
-        if system == 'Darwin':
+        if system == u'Darwin':
             os.write(tmp_fd, b_DUMMY_CA_CERT)
             # Default Homebrew path for OpenSSL certs
             paths_checked.append('/usr/local/etc/openssl')


Test patch:
Repository: ansible/ansible

Issue:
Error message about conflicting issue should list the conflicting issues


##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
Error Message

##### ANSIBLE VERSION
```
ansible 2.2.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```

##### CONFIGURATION

##### OS / ENVIRONMENT
N/A
##### SUMMARY
The error message says that there are conflicting action statements. Since ansible knows which ones at this point it would help to print them in the error message. This would make it more clear for new users which lines are the problem 

##### STEPS TO REPRODUCE

<!--- Paste example playbooks or commands between quotes below -->
```
- hosts: localhost
  gather_facts: no

  tasks:
  - name: task with 2 actions
    shell: echo foo
    register: result
    debug: var=result
                            
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
ERROR! conflicting action statements: shell, debug
##### ACTUAL RESULTS
ERROR! conflicting action statements

Error message about conflicting issue should list the conflicting issues


##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
Error Message

##### ANSIBLE VERSION
```
ansible 2.2.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```

##### CONFIGURATION

##### OS / ENVIRONMENT
N/A
##### SUMMARY
The error message says that there are conflicting action statements. Since ansible knows which ones at this point it would help to print them in the error message. This would make it more clear for new users which lines are the problem 

##### STEPS TO REPRODUCE

<!--- Paste example playbooks or commands between quotes below -->
```
- hosts: localhost
  gather_facts: no

  tasks:
  - name: task with 2 actions
    shell: echo foo
    register: result
    debug: var=result
                            
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
ERROR! conflicting action statements: shell, debug
##### ACTUAL RESULTS
ERROR! conflicting action statements



Discussion:

Resolving patch:
diff --git a/lib/ansible/parsing/mod_args.py b/lib/ansible/parsing/mod_args.py
--- a/lib/ansible/parsing/mod_args.py
+++ b/lib/ansible/parsing/mod_args.py
@@ -287,7 +287,7 @@ def parse(self):
             if item in module_loader or item in ['meta', 'include', 'include_role']:
                 # finding more than one module name is a problem
                 if action is not None:
-                    raise AnsibleParserError("conflicting action statements", obj=self._task_ds)
+                    raise AnsibleParserError("conflicting action statements: %s, %s" % (action, item), obj=self._task_ds)
                 action = item
                 thing = value
                 action, args = self._normalize_parameters(thing, action=action, additional_args=additional_args)


Test patch: