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

Issue:
docker module reloads unnecessary if log_driver for daemon is not default
Running devel, this of code is the exact problem:

``` python
if self.ensure_capability('log_driver', False):
                expected_log_driver = self.module.params.get('log_driver') or 'json-file'
                actual_log_driver = container['HostConfig']['LogConfig']['Type']
                if actual_log_driver != expected_log_driver:
                    self.reload_reasons.append('log_driver ({0} => {1})'.format(actual_log_driver, expected_log_driver))
                    differing.append(container)
                    continue
```

When running with `state=reloaded`, if your docker-daemon has a default log and you have not specified the log_driver then a comparison is always made to `'json-file'`. So in my case where I have journald as the default on all my hosts, the driver will always restart my containers - even though it doesn't actually pass `'json-file'` to the containers on the restart.

If expected log_driver is `self.module.params.get('log_driver')` is None, it should be assumed that no changes are actually specified - or (but I do not yet know how to do this) - the daemon default driver should be used instead.

Related to #1251

EDIT: Looks like the driver should just add a call to docker_py's info() module to check the default settings.



Discussion:

Resolving patch:
diff --git a/cloud/docker/docker.py b/cloud/docker/docker.py
--- a/cloud/docker/docker.py
+++ b/cloud/docker/docker.py
@@ -1017,6 +1017,7 @@ def get_differing_containers(self):
 
         running = self.get_running_containers()
         current = self.get_inspect_containers(running)
+        defaults = self.client.info()
 
         #Get API version
         api_version = self.client.version()['ApiVersion']
@@ -1288,7 +1289,7 @@ def get_differing_containers(self):
             # LOG_DRIVER
 
             if self.ensure_capability('log_driver', False):
-                expected_log_driver = self.module.params.get('log_driver') or 'json-file'
+                expected_log_driver = self.module.params.get('log_driver') or defaults['LoggingDriver']
                 actual_log_driver = container['HostConfig']['LogConfig']['Type']
                 if actual_log_driver != expected_log_driver:
                     self.reload_reasons.append('log_driver ({0} => {1})'.format(actual_log_driver, expected_log_driver))


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Nonexistent exception in ec2_asg.py
##### ISSUE TYPE

Bug Report
##### COMPONENT NAME

ec2_elb
##### ANSIBLE VERSION

N/A
##### SUMMARY

The EC2 autoscaling module tries to catch a nonexist exception `boto.exception.InvalidInstance` at https://github.com/ansible/ansible-modules-core/commit/b2df875e78d6be12409bf7a3926c005b23993170#diff-689b2e5ce09076c21c9915e50f8a9140R292.  This should be handled like https://github.com/ansible/ansible-modules-core/blob/devel/cloud/amazon/ec2_elb.py#L243 instead.

Nonexistent exception in ec2_asg.py
##### ISSUE TYPE

Bug Report
##### COMPONENT NAME

ec2_elb
##### ANSIBLE VERSION

N/A
##### SUMMARY

The EC2 autoscaling module tries to catch a nonexist exception `boto.exception.InvalidInstance` at https://github.com/ansible/ansible-modules-core/commit/b2df875e78d6be12409bf7a3926c005b23993170#diff-689b2e5ce09076c21c9915e50f8a9140R292.  This should be handled like https://github.com/ansible/ansible-modules-core/blob/devel/cloud/amazon/ec2_elb.py#L243 instead.



Discussion:

Resolving patch:
diff --git a/cloud/amazon/ec2_asg.py b/cloud/amazon/ec2_asg.py
--- a/cloud/amazon/ec2_asg.py
+++ b/cloud/amazon/ec2_asg.py
@@ -334,8 +334,12 @@ def elb_healthy(asg_connection, elb_connection, module, group_name):
         # but has not yet show up in the ELB
         try:
             lb_instances = elb_connection.describe_instance_health(lb, instances=instances)
-        except boto.exception.InvalidInstance:
-            pass
+        except boto.exception.BotoServerError as e:
+            if e.error_code == 'InvalidInstance':
+                return None
+
+            module.fail_json(msg=str(e))
+
         for i in lb_instances:
             if i.state == "InService":
                 healthy_instances.append(i.instance_id)


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Replace outdated idiom choices=BOOLEANS
Argument specs used to use `choices=BOOLEANS` to specify that an argument should be True or False.  We've since enhanced the argument_spec code so that `type='bool'` does the job.  We need to go through the modules and change this over at some point.

Find modules needing updating this way:

```
grep BOOLEAN modules/core -r
```

Change lines within the module like this:

```
- is_ready = dict(choices=BOOLEANS, default=False),
+ is_ready = dict(type='bool', default=False),
```



Discussion:

Resolving patch:
diff --git a/cloud/openstack/os_ironic.py b/cloud/openstack/os_ironic.py
--- a/cloud/openstack/os_ironic.py
+++ b/cloud/openstack/os_ironic.py
@@ -183,17 +183,12 @@ def _choose_id_value(module):
     return None
 
 
-def _is_value_true(value):
-    true_values = [True, 'yes', 'Yes', 'True', 'true']
-    if value in true_values:
-        return True
-    return False
 
 
 def _choose_if_password_only(module, patch):
     if len(patch) is 1:
-        if 'password' in patch[0]['path'] and _is_value_true(
-                module.params['skip_update_of_masked_password']):
+        if 'password' in patch[0]['path'] and
+                module.params['skip_update_of_masked_password']:
             # Return false to aabort update as the password appears
             # to be the only element in the patch.
             return False
@@ -219,7 +214,7 @@ def main():
         properties=dict(type='dict', default={}),
         ironic_url=dict(required=False),
         chassis_uuid=dict(required=False),
-        skip_update_of_masked_password=dict(required=False, choices=BOOLEANS),
+        skip_update_of_masked_password=dict(required=False, type='bool'),
         state=dict(required=False, default='present')
     )
     module_kwargs = openstack_module_kwargs()


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Mount fails if ansible user has no read permission inside mount
##### Issue Type: Bug report
##### Ansible Version: 1.9.3
##### Ansible Configuration: Default
##### Environment: openSuSE 13.2
##### Summary:

A bug in python os.path makes the mount module fail when
- state=mounted
- filesystem: nfs (probably most others as well)
- the mount is already present
- the ansible user has no read permission inside the mount

The reason for this is that ansible uses os.path.ismount(mountpath) which fails if pointed at a mount inside which the user has no read permission, see http://bugs.python.org/issue2466.
This is quite common if you use nfs with root_squash or kerberos.

The python-bug is quite old and unfixed, so maybe it's worthwhile to have a workaround in ansible. The function in question is 10 lines of python.
##### Steps To Reproduce:

See Summary
##### Expected Results:

Should return 'ok'
##### Actual Results:

returns failed



Discussion:
[module: system/mount.py]

Hi @robinro -- thanks for submitting this bug report.

@ansible/core team -- pinging you to bring this bug report to your attention. 

Python is rather slow in merging this. Is it an option to put the fixed version of os.path.ismount directly in ansible and use it for all python versions where this is broken?

@robinro submit a PR


Resolving patch:
diff --git a/system/mount.py b/system/mount.py
--- a/system/mount.py
+++ b/system/mount.py
@@ -231,10 +231,10 @@ def mount(module, **kwargs):
     mount_bin = module.get_bin_path('mount')
 
     name = kwargs['name']
-    
+
     cmd = [ mount_bin, ]
-    
-    if os.path.ismount(name):
+
+    if ismount(name):
         cmd += [ '-o', 'remount', ]
 
     if get_platform().lower() == 'freebsd':
@@ -311,7 +311,7 @@ def main():
     if state == 'absent':
         name, changed = unset_mount(module, **args)
         if changed and not module.check_mode:
-            if os.path.ismount(name):
+            if ismount(name):
                 res,msg  = umount(module, **args)
                 if res:
                     module.fail_json(msg="Error unmounting %s: %s" % (name, msg))
@@ -325,7 +325,7 @@ def main():
         module.exit_json(changed=changed, **args)
 
     if state == 'unmounted':
-        if os.path.ismount(name):
+        if ismount(name):
             if not module.check_mode:
                 res,msg  = umount(module, **args)
                 if res:
@@ -345,7 +345,7 @@ def main():
         name, changed = set_mount(module, **args)
         if state == 'mounted':
             res = 0
-            if os.path.ismount(name):
+            if ismount(name):
                 if changed and not module.check_mode:
                     res,msg = mount(module, **args)
             elif 'bind' in args.get('opts', []):
@@ -375,4 +375,6 @@ def main():
 
 # import module snippets
 from ansible.module_utils.basic import *
+from ansible.module_utils.ismount import *
+
 main()


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Cloudformation module: requiring template during stack deletion
ansible 1.9.4, OS X 10.11

According to the documentation 'template' argument for cloudformation module required only when state=present. But execution failed when I try to delete stack without specifying template:

```
 ansible -i hosts localhost -m cloudformation -a 'stack_name=my state=absent'
 127.0.0.1 | FAILED >> {
     "failed": true, 
     "msg": "missing required arguments: template"
 }
```



Discussion:
[module: cloud/amazon/cloudformation.py]

@awasilyev -- Thanks for submitting this bug report.

@jsmartin --  thanks in advance for taking a look at this bug report and for your ongoing work in maintaining this module.

You can workaround this issue by setting any existing template (or creating a fake one). The code will read it but it won't be used afterwise, yet still allows you to delete the stack.


Resolving patch:
diff --git a/cloud/amazon/cloudformation.py b/cloud/amazon/cloudformation.py
--- a/cloud/amazon/cloudformation.py
+++ b/cloud/amazon/cloudformation.py
@@ -258,9 +258,6 @@ def main():
     if not HAS_BOTO:
         module.fail_json(msg='boto required for this module')
 
-    if module.params['template'] is None and module.params['template_url'] is None:
-        module.fail_json(msg='Either template or template_url expected')
-
     state = module.params['state']
     stack_name = module.params['stack_name']
 


Test patch:
Repository: ansible/ansible-modules-core

Issue:
docker module: pull all version of images if version is null
In case of mistakenly specify 'null' as image version for docker module it tries to pull all versions of this image, wasting disk space. Reproduced both in 1.9.4 and 2.0

Steps to reproduce:
docker 1.9.1
ansible -m docker -a 'state=reloaded name=test net=bridge image=centos:' -c local localhost

Actual result:
docker tries to pull all existing centos image version

Expected result:
pulling only centos:latest or failing with 'image not found' error



Discussion:

Resolving patch:
diff --git a/cloud/docker/docker.py b/cloud/docker/docker.py
--- a/cloud/docker/docker.py
+++ b/cloud/docker/docker.py
@@ -569,6 +569,8 @@ def get_split_image_tag(image):
         resource, tag = resource.split(':', 1)
         if registry:
             resource = '/'.join((registry, resource))
+        if tag == "":
+            tag = "latest"
     else:
         tag = "latest"
         resource = image


Test patch:
Repository: ansible/ansible-modules-core

Issue:
apt module installs python-apt in check mode
##### Issue Type:

Bug Report
##### Ansible Version:

```
ansible 2.1.0 (devel 9286143b53) last updated 2016/02/11 04:45:11 (GMT +000)
  lib/ansible/modules/core: (detached HEAD 9fc4ed0458) last updated 2016/02/11 04:45:24 (GMT +000)
  lib/ansible/modules/extras: (detached HEAD 6aeb2ab6cf) last updated 2016/02/11 04:45:24 (GMT +000)
  config file =
  configured module search path = Default w/o overrides
```
##### Ansible Configuration:

N/A
##### Environment:

Ubuntu 14.04 LTS
##### Summary:

The apt module automatically installs python-apt if needed, even if running in check mode.
##### Steps To Reproduce:

```
sudo apt-get remove python-apt -yqq
ansible -m apt -a 'name=nginx state=absent' --check localhost
```
##### Expected Results:

The apt module should fail with an error indicating python-apt is not installed.
##### Actual Results:

The python-apt module is automatically installed and the module successfully returns.



Discussion:

Resolving patch:
diff --git a/packaging/os/apt.py b/packaging/os/apt.py
--- a/packaging/os/apt.py
+++ b/packaging/os/apt.py
@@ -579,6 +579,8 @@ def main():
     module.run_command_environ_update = APT_ENV_VARS
 
     if not HAS_PYTHON_APT:
+        if module.check_mode:
+            module.fail_json(msg="python-apt must be installed to use check mode")
         try:
             module.run_command('apt-get update && apt-get install python-apt -y -q --force-yes', use_unsafe_shell=True, check_rc=True)
             global apt, apt_pkg


Test patch:
Repository: ansible/ansible-modules-core

Issue:
[v2.1] git module always reports changed --check mode when version= is not explicitly specified
**Ansible Version**

ansible 2.1.0 (devel c485981d1a) last updated 2016/02/12 08:50:29 (GMT +300)
  lib/ansible/modules/core: (detached HEAD 8d126bd877) last updated 2016/02/12 08:50:23 (GMT +300)
  lib/ansible/modules/extras: (detached HEAD f6c5ed987f) last updated 2016/02/12 08:50:23 (GMT +300)

**Summary**

This is my task:

``` yaml
- git: repo=git@fridge.pov.lt:/git/{{ item }}.git dest=/var/www/{{ item }}
  with_items:
    - zope3.pov.lt
```

When I run `ansible-playbook` with `--check`, this task always reports `changed`.  In verbose mode:

```
changed: [fridge] => (item=zope3.pov.lt) => {"after": "d9872a99c4b4b411b3a295b2606e2d7b5f757f93", "before": "d9872a99c4b4b411b3a295b2606e2d7b5f757f93", "changed": true, "item": "zope3.pov.lt"}
```

Note how `before` and `after` point to the same git commit!

If I run _without_ `--check`, Ansible correctly reports

```
ok: [fridge] => (item=zope3.pov.lt) => {"after": "d9872a99c4b4b411b3a295b2606e2d7b5f757f93", "before": "d9872a99c4b4b411b3a295b2606e2d7b5f757f93", "changed": false, "item": "zope3.pov.lt", "local_changes": false, "submodules_changed": false}
```

This is a regression since 2.0.0.2.



Discussion:
I've traced this down to the following code in git.py:

``` python
    repo_updated = None
    ...
    else:
        # else do a pull
        ...
        if before == remote_head:
            if local_mods:   # <-- nope
                ...
            elif is_remote_tag(git_path, module, dest, repo, version):   # <-- nope
                ...
            else:
                # if the remote is a branch and we have the branch locally, exit early
                if version in get_branches(git_path, module, dest):   # <-- nope
                    ...
        if repo_updated is None:  # <-- yep, nothing changed it
            if module.check_mode:
                module.exit_json(changed=True, before=before, after=remote_head)
```

Since I haven't explicitly specified `version`, it's `"HEAD"`.


Resolving patch:
diff --git a/source_control/git.py b/source_control/git.py
--- a/source_control/git.py
+++ b/source_control/git.py
@@ -819,6 +819,8 @@ def main():
             if local_mods:
                 module.exit_json(changed=True, before=before, after=remote_head,
                     msg="Local modifications exist")
+            elif version == 'HEAD':
+                repo_updated = False
             elif is_remote_tag(git_path, module, dest, repo, version):
                 # if the remote is a tag and we have the tag locally, exit early
                 if version in get_tags(git_path, module, dest):


Test patch:
Repository: ansible/ansible-modules-core

Issue:
apache2_module hangs with "WARNING: The following essential module will be disabled."
I have this code in my playbook:

```
- apache2_module: name={{item}} state=absent
  with_items:
    - autoindex
    - negotiation
```

However someone decided that autoindex and negotiation both are "essential", so when I try to disable them I get this warning:

```
# a2dismod autoindex
WARNING: The following essential module will be disabled.
This might result in unexpected behavior and should NOT be done
unless you know exactly what you are doing!
 autoindex

To continue type in the phrase 'Yes, do as I say!' or retry by passing '-f':
```

and expects me to actually type "Yes, do as I say!" (WTF?!?) if I don't provide "-f". The ansible module does not provide that -f parameter, so it locks up.

As weird as that is, I think there _at least_ should be a "force=true" option in apache2_module - or -f should be default.

(Not sure if that's true for all "a2dismod" instances because there is a suspiciously low amount of Google results (none). It is at least there for apache2 currently installed from dotdeb.org)



Discussion:
[module: web_infrastructure/apache2_module.py]

@BlaM Thanks for submitting this bug report.

@berendt thanks in advance for taking a look at this bug report and for your ongoing work in maintaining this module.


Resolving patch:
diff --git a/web_infrastructure/apache2_module.py b/web_infrastructure/apache2_module.py
--- a/web_infrastructure/apache2_module.py
+++ b/web_infrastructure/apache2_module.py
@@ -29,6 +29,12 @@
      description:
         - name of the module to enable/disable
      required: true
+   force:
+     description:
+        - force disabling of default modules and override Debian warnings
+     required: false
+     choices: ['yes', 'no']
+     default: no
    state:
      description:
         - indicate the desired state of the resource
@@ -50,10 +56,14 @@
 
 def _disable_module(module):
     name = module.params['name']
+    force = module.params['force']
     a2dismod_binary = module.get_bin_path("a2dismod")
     if a2dismod_binary is None:
         module.fail_json(msg="a2dismod not found.  Perhaps this system does not use a2dismod to manage apache")
 
+    if force:
+        a2dismod_binary += ' -f'
+
     result, stdout, stderr = module.run_command("%s %s" % (a2dismod_binary, name))
 
     if re.match(r'.*\b' + name + r' already disabled', stdout, re.S|re.M):
@@ -82,6 +92,7 @@ def main():
     module = AnsibleModule(
         argument_spec = dict(
             name  = dict(required=True),
+            force = dict(required=False, type='bool', default=False),
             state = dict(default='present', choices=['absent', 'present'])
         ),
     )


Test patch:
Repository: ansible/ansible-modules-core

Issue:
ec2_elb_lb should allow creation of LBCookieStickinessPolicyType with no expiration
This is related to the work done by @haad in #1190 

Amazon and Boto both allow for the creation of a LBCookieStickinessPolicyType that has no expiration time set. However the ec2_elb_lb module requires expiration to be set for type loadbalancer.

Desired Config Example:

```
  ec2_elb_lb:
    name: "example-lb"
    state: present
    region: "us-west-2"
    security_group_ids: "a384j874"
    listeners: 
      - protocol: http
        load_balancer_port: 80
        instance_port: 80
    health_check: 
        ping_protocol: http 
        ping_port: 80
        ping_path: "/ping.php"
        response_timeout: 5
        interval: 30 
        unhealthy_threshold: 2
        healthy_threshold: 2
    scheme: "internet-facing"
    cross_az_load_balancing: yes
    stickiness: 
        type: loadbalancer
        enabled: yes
  register: elb
```



Discussion:
You can set `expiration: 0`, which has exactly the same effect on AWS side, but this leads to another issue: The task then is always considered as `changed`.


Resolving patch:
diff --git a/cloud/amazon/ec2_elb_lb.py b/cloud/amazon/ec2_elb_lb.py
--- a/cloud/amazon/ec2_elb_lb.py
+++ b/cloud/amazon/ec2_elb_lb.py
@@ -888,7 +888,7 @@ def _set_listener_policy(self, listeners_dict, policy=[]):
     def _set_stickiness_policy(self, elb_info, listeners_dict, policy, **policy_attrs):
         for p in getattr(elb_info.policies, policy_attrs['attr']):
             if str(p.__dict__['policy_name']) == str(policy[0]):
-                if str(p.__dict__[policy_attrs['dict_key']]) != str(policy_attrs['param_value']):
+                if str(p.__dict__[policy_attrs['dict_key']]) != str(policy_attrs['param_value'] or 0):
                     self._set_listener_policy(listeners_dict)
                     self._update_policy(policy_attrs['param_value'], policy_attrs['method'], policy_attrs['attr'], policy[0])
                     self.changed = True


Test patch:
Repository: ansible/ansible-modules-core

Issue:
ec2_ami AttributeError: 'AnsibleModule' object has no attribute 'json_fail'
##### Issue Type:

<!-- Please pick one and delete the rest: -->
- Bug Report
##### Plugin Name:

<!-- Name of the plugin/module/task -->

ec2_ami
##### Ansible Version:

```
ansible 2.1.0 devel 
```
##### Ansible Configuration:

N/A
##### Environment:

N/A
##### Summary:

There is a typo on line 380. it should be module.fail_json

ec2_ami throws an exception when ec2_connect fails:
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
  File "<stdin>", line 2727, in <module>
  File "<stdin>", line 381, in main
AttributeError: 'AnsibleModule' object has no attribute 'json_fail'

fatal: [54.193.26.211]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_name": "ec2_ami"}, "parsed": false}
##### Steps To Reproduce:
1. set bad AWS credentials
2. try to create an AMI with the ec2_ami modules
3. AttributeError: 'AnsibleModule' object has no attribute 'json_fail'
##### Expected Results:

Standard ansible fatal error msg sould be printed.
##### Actual Results:

An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
  File "<stdin>", line 2727, in <module>
  File "<stdin>", line 381, in main
AttributeError: 'AnsibleModule' object has no attribute 'json_fail'



Discussion:

Resolving patch:
diff --git a/cloud/amazon/ec2_ami.py b/cloud/amazon/ec2_ami.py
--- a/cloud/amazon/ec2_ami.py
+++ b/cloud/amazon/ec2_ami.py
@@ -377,7 +377,7 @@ def main():
     try:
         ec2 = ec2_connect(module)
     except Exception, e:
-        module.json_fail(msg="Error while connecting to aws: %s" % str(e))
+        module.fail_json(msg="Error while connecting to aws: %s" % str(e))
 
     if module.params.get('state') == 'absent':
         if not module.params.get('image_id'):


Test patch: