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

Issue:
ini_file - Insert missing option line before blank lines at the end of the section
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

ini_file
##### ANSIBLE VERSION

```
ansible 2.1.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```
##### CONFIGURATION

N/A
##### OS / ENVIRONMENT

N/A
##### SUMMARY

<!--- Explain the problem briefly -->

New lines are added to an existing section after blank lines separating sections, but should instead be added before blank lines at the end of a section.
##### STEPS TO REPRODUCE

Use ini_file to add a new line to a file.

Given test.ini:

```
[sect1]
opt1 = val1

[sect2]
opt2 = val2
```

Run this test command:

```
ansible -c local -m ini_file -a 'dest=test.ini section=sect1 option=opt13 value=val13' localhost
```
##### EXPECTED RESULTS

test.ini should look like this:

```
[sect1]
opt1 = val1
opt3 = val3

[sect2]
opt2 = val2
```
##### ACTUAL RESULTS

This file is still technically correct but just looks a bit misleading as opt3 is grouped closer to [sect2].

```
[sect1]
opt1 = val1

opt3 = val3
[sect2]
opt2 = val2
```



Discussion:

Resolving patch:
diff --git a/files/ini_file.py b/files/ini_file.py
--- a/files/ini_file.py
+++ b/files/ini_file.py
@@ -155,8 +155,12 @@ def do_ini(module, filename, section=None, option=None, value=None, state='prese
             if within_section:
                 if state == 'present':
                     # insert missing option line at the end of the section
-                    ini_lines.insert(index, assignment_format % (option, value))
-                    changed = True
+                    for i in range(index, 0, -1):
+                        # search backwards for previous non-blank or non-comment line
+                        if not re.match(r'^[ \t]*([#;].*)?$', ini_lines[i - 1]):
+                            ini_lines.insert(i, assignment_format % (option, value))
+                            changed = True
+                            break
                 elif state == 'absent' and not option:
                     # remove the entire section
                     del ini_lines[section_start:index]


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

Issue:
Fix #4412: os_security_group_rule support numbered protocols
##### ISSUE TYPE
- Bugfix Pull Request
##### COMPONENT NAME

cloud/openstack/os_security_group_rule.py
##### ANSIBLE VERSION

```
ansible 2.1.1.0
  config file = 
  configured module search path = Default w/o overrides
```
##### SUMMARY

Bugfix correctly points out lack of VRRP support by way of numbered protocol.  This commit adds this functionality, including example usage in the documentation.



Discussion:
Thanks @davidjpeacock. To the current maintainers, @emonty, @shrews, @juliakreger, @j2sol, @rcarrillocruz please review according to guidelines (http://docs.ansible.com/ansible/developing_modules.html#module-checklist) and comment with text 'shipit', 'needs_revision' or 'close_me' as appropriate.

[This message brought to you by your friendly Ansibull-bot.]


Resolving patch:
diff --git a/cloud/openstack/os_security_group_rule.py b/cloud/openstack/os_security_group_rule.py
--- a/cloud/openstack/os_security_group_rule.py
+++ b/cloud/openstack/os_security_group_rule.py
@@ -39,7 +39,7 @@
    protocol:
       description:
         - IP protocols TCP UDP ICMP 112 (VRRP)
-      choices: ['tcp', 'udp', 'icmp', 112, None]
+      choices: ['tcp', 'udp', 'icmp', '112', None]
       default: None
    port_range_min:
       description:
@@ -257,7 +257,7 @@ def main():
         # NOTE(Shrews): None is an acceptable protocol value for
         # Neutron, but Nova will balk at this.
         protocol         = dict(default=None,
-                                choices=[None, 'tcp', 'udp', 'icmp', 112]),
+                                choices=[None, 'tcp', 'udp', 'icmp', '112']),
         port_range_min   = dict(required=False, type='int'),
         port_range_max   = dict(required=False, type='int'),
         remote_ip_prefix = dict(required=False, default=None),


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

Issue:
junos_package.py: package_version undefined
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

junos_package
##### ANSIBLE VERSION

devel
##### CONFIGURATION
##### OS / ENVIRONMENT
##### SUMMARY

https://github.com/ansible/ansible-modules-core/blame/devel/network/junos/junos_package.py#L141

`wants_ver = module.params['version'] or package_version(module)`

I can't find anywhere in the `ansible/ansible` code base where `package_version` is defined



Discussion:
<!-- @gundalow: Thanks for filing this bug report! -->

@privateip, @gundalow, ping. This issue is waiting on your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_bug_new --->

@privateip, @gundalow, ping. This issue is still waiting on your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_renotify_maintainer --->

Reviewed, needs fixing. Some old code left from before the refactoring


Resolving patch:
diff --git a/network/junos/junos_package.py b/network/junos/junos_package.py
--- a/network/junos/junos_package.py
+++ b/network/junos/junos_package.py
@@ -92,6 +92,7 @@
     src: junos-vsrx-12.1X46-D10.2-domestic.tgz
     reboot: no
 """
+from ansible.module_utils.junos import NetworkModule
 
 try:
     from jnpr.junos.utils.sw import SW
@@ -127,8 +128,8 @@ def main():
         transport=dict(default='netconf', choices=['netconf'])
     )
 
-    module = get_module(argument_spec=spec,
-                        supports_check_mode=True)
+    module = NetworkModule(argument_spec=spec,
+                           supports_check_mode=True)
 
     if not HAS_SW:
         module.fail_json(msg='Missing jnpr.junos.utils.sw module')
@@ -137,8 +138,8 @@ def main():
 
     do_upgrade = module.params['force'] or False
     if not module.params['force']:
-        has_ver = module.get_facts().get('version')
-        wants_ver = module.params['version'] or package_version(module)
+        has_ver = module.connection.get_facts().get('version')
+        wants_ver = module.params['version']
         do_upgrade = has_ver != wants_ver
 
     if do_upgrade:
@@ -148,8 +149,6 @@ def main():
 
     module.exit_json(**result)
 
-from ansible.module_utils.basic import *
-from ansible.module_utils.junos import *
 
 if __name__ == '__main__':
     main()


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

Issue:
postgresql_db inverts the 'changed' logic in check mode when state=absent
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

postgresql_db
##### ANSIBLE VERSION

```
ansible 2.1.1.0
  config file = 
  configured module search path = Default w/o overrides
```
##### SUMMARY

I've a task that tries to remove a PostgreSQL database.  When I run it in --check mode, it says "changed" if the database doesn't exist, and says "not changed" if the database exists. This is exactly the opposite of what it should say.

<!--
##### STEPS TO REPRODUCE

```

```

##### EXPECTED RESULTS

##### ACTUAL RESULTS
```

```
-->



Discussion:

Resolving patch:
diff --git a/database/postgresql/postgresql_db.py b/database/postgresql/postgresql_db.py
old mode 100644
new mode 100755
--- a/database/postgresql/postgresql_db.py
+++ b/database/postgresql/postgresql_db.py
@@ -288,11 +288,11 @@ def main():
     try:
         if module.check_mode:
             if state == "absent":
-                changed = not db_exists(cursor, db)
+                changed = db_exists(cursor, db)
             elif state == "present":
                 changed = not db_matches(cursor, db, owner, template, encoding,
                                          lc_collate, lc_ctype)
-            module.exit_json(changed=changed,db=db)
+            module.exit_json(changed=changed, db=db)
 
         if state == "absent":
             try:


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

Issue:
iam_cert module error : value of dup_ok must be one of: False,True, got: True
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

iam_cert
##### ANSIBLE VERSION

```
ansible 2.1.1.0
  config file = /Users/ABC16gb/Documents/Projects/AWS/jenkins/ansible/ansible.cfg
  configured module search path = Default w/o overrides

```
##### CONFIGURATION

ansible.cfg : 
[defaults]
host_file = inventory/ec2.py
inventory = inventory/
host_key_checking = False

[ssh_connection]
control_path = %(directory)s/%%h-%%r
##### OS / ENVIRONMENT

NA
##### SUMMARY

Get the above mentioned error even when dup_ok is set to True
##### STEPS TO REPRODUCE

```
- name: "SSL: self-signed: Upload certificate into AWS/IAM"
  iam_cert:
    name: "{{ aws_name_tag }}"
    state: present
    cert: "{{ ssl_cert_path_local }}"
    key: "{{ ssl_key_path_local }}"
    dup_ok: True

```
##### EXPECTED RESULTS

Upload certificates
##### ACTUAL RESULTS

Fatal error

```
localhost> ESTABLISH LOCAL CONNECTION FOR USER: abc16gb
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo $HOME/.ansible/tmp/ansible-tmp-1474370591.44-108967808855571 `" && echo ansible-tmp-1474370591.44-108967808855571="` echo $HOME/.ansible/tmp/ansible-tmp-1474370591.44-108967808855571 `" ) && sleep 0'
<localhost> PUT /var/folders/c1/mmksrrsd2xz59lm25277m4cc0000gn/T/tmp02Kpb9 TO /Users/tesco16gb/.ansible/tmp/ansible-tmp-1474370591.44-108967808855571/iam_cert
<localhost> EXEC /bin/sh -c 'LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 /usr/bin/python /Users/tesco16gb/.ansible/tmp/ansible-tmp-1474370591.44-108967808855571/iam_cert; rm -rf "/Users/tesco16gb/.ansible/tmp/ansible-tmp-1474370591.44-108967808855571/" > /dev/null 2>&1 && sleep 0'


fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "invocation": {"module_args": {"cert": "dev-jenkins.crt", "dup_ok": "True", "key": "dev-jenkins.key", "name": "dev-jenkins", "path": "/", "state": "present", "validate_certs": true}, "module_name": "iam_cert"}, "msg": "value of dup_ok must be one of: False,True, got: True"}

```



Discussion:
<!-- @endling1: Thanks for filing this bug report! -->

@ansible ping, this issue is waiting for your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_bug_new --->

I see this issue has been addressed on devel (2.2) 8879931f0cd727244587b6e58a7279d9125c96a2 but I see no backport and IMHO the choices list `choices=[False, True]`should be removed


Resolving patch:
diff --git a/cloud/amazon/iam_cert.py b/cloud/amazon/iam_cert.py
--- a/cloud/amazon/iam_cert.py
+++ b/cloud/amazon/iam_cert.py
@@ -232,7 +232,7 @@ def main():
         new_name=dict(default=None, required=False),
         path=dict(default='/', required=False),
         new_path=dict(default=None, required=False),
-        dup_ok=dict(default=False, required=False, choices=[False, True])
+        dup_ok=dict(default=False, required=False, type='bool')
     )
     )
 


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

Issue:
docker_service: Failed to cast value to int in scale parameter while using variable
Partially copied from https://github.com/ansible/ansible/issues/17017
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

docker_service
##### ANSIBLE VERSION

```
ansible 2.1.1.0
```
##### CONFIGURATION

No special configuration required
##### OS / ENVIRONMENT

<!---
Mention the OS you are running Ansible from, and the OS you are
managing, or say “N/A” for anything that is not platform-specific.
-->
##### SUMMARY

Throws `unsupported operand type(s) for -: 'str' and 'int'"` while using variable in docker_service scale parameter even if variable is casted to int like `{{ num_procs | int }}`
##### STEPS TO REPRODUCE

<!---
For bugs, show exactly how to reproduce the problem.
For new features, show how the feature would be used.
-->

Play:

```
- hosts: all
  roles:
  - role: test

```

Role:

```

---
- set_fact: num_instances=3

- docker_service:
    project_name: webserver
    scale:
        nginx: "{{ num_instances }}"
    definition:
        version: "2"
        services:
            nginx:
                image: nginx

```
##### EXPECTED RESULTS

Three running nginx containers.
##### ACTUAL RESULTS

`Error scaling web - unsupported operand type(s) for -: 'str' and 'int'"`



Discussion:
<!-- @jaydg: Thanks for filing this bug report! -->

@ansible ping, this issue is waiting for your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_bug_new --->


Resolving patch:
diff --git a/cloud/docker/docker_service.py b/cloud/docker/docker_service.py
--- a/cloud/docker/docker_service.py
+++ b/cloud/docker/docker_service.py
@@ -655,7 +655,7 @@ def cmd_up(self):
                     detached=detached,
                     remove_orphans=self.remove_orphans)
             except Exception as exc:
-                self.client.fail("Error bring %s up - %s" % (self.project.name, str(exc)))
+                self.client.fail("Error starting project - %s" % str(exc))
 
         if self.stopped:
             result.update(self.cmd_stop(service_names))
@@ -804,7 +804,7 @@ def cmd_down(self):
             try:
                 self.project.down(image_type, self.remove_volumes, self.remove_orphans)
             except Exception as exc:
-                self.client.fail("Error bringing %s down - %s" % (self.project.name, str(exc)))
+                self.client.fail("Error stopping project - %s" % str(exc))
 
         return result
 
@@ -877,7 +877,7 @@ def cmd_scale(self):
                         result['actions'][service.name]['scale'] = self.scale[service.name] - len(containers)
                     if not self.check_mode:
                         try:
-                            service.scale(self.scale[service.name])
+                            service.scale(int(self.scale[service.name]))
                         except Exception as exc:
                             self.client.fail("Error scaling %s - %s" % (service.name, str(exc)))
         return result


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

Issue:
docker_service: timeout option not respected
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

docker_service
##### ANSIBLE VERSION

```
ansible 2.1.0.0
```
##### SUMMARY

The `timeout` option specified in a docker_service task seems to be not actually used.
##### STEPS TO REPRODUCE

SEE https://github.com/ansible/ansible-modules-core/blob/devel/cloud/docker/docker_service.py#L837-L862



Discussion:
<!-- @shaung: Thanks for filing this bug report! -->

@ansible ping, this issue is waiting for your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_bug_new --->


Resolving patch:
diff --git a/cloud/docker/docker_service.py b/cloud/docker/docker_service.py
--- a/cloud/docker/docker_service.py
+++ b/cloud/docker/docker_service.py
@@ -466,9 +466,11 @@
     from compose.cli.command import project_from_options
     from compose.service import ConvergenceStrategy
     from compose.cli.main import convergence_strategy_from_opts, build_action_from_opts, image_type_from_opt
+    from compose.const import DEFAULT_TIMEOUT
 except ImportError as exc:
     HAS_COMPOSE = False
     HAS_COMPOSE_EXC = str(exc)
+    DEFAULT_TIMEOUT = 10
 
 from ansible.module_utils.docker_common import *
 
@@ -653,7 +655,8 @@ def cmd_up(self):
                     strategy=converge,
                     do_build=do_build,
                     detached=detached,
-                    remove_orphans=self.remove_orphans)
+                    remove_orphans=self.remove_orphans,
+                    timeout=self.timeout)
             except Exception as exc:
                 self.client.fail("Error bring %s up - %s" % (self.project.name, str(exc)))
 
@@ -828,7 +831,7 @@ def cmd_stop(self, service_names):
 
         if not self.check_mode and result['changed']:
             try:
-                self.project.stop(service_names=service_names)
+                self.project.stop(service_names=service_names, timeout=self.timeout)
             except Exception as exc:
                 self.client.fail("Error stopping services for %s - %s" % (self.project.name, str(exc)))
 
@@ -855,7 +858,7 @@ def cmd_restart(self, service_names):
 
         if not self.check_mode and result['changed']:
             try:
-                self.project.restart(service_names=service_names)
+                self.project.restart(service_names=service_names, timeout=self.timeout)
             except Exception as exc:
                 self.client.fail("Error restarting services for %s - %s" % (self.project.name, str(exc)))
 
@@ -903,7 +906,8 @@ def main():
         dependencies=dict(type='bool', default=True),
         pull=dict(type='bool', default=False),
         nocache=dict(type='bool', default=False),
-        debug=dict(type='bool', default=False)
+        debug=dict(type='bool', default=False),
+        timeout=dict(type='int', default=DEFAULT_TIMEOUT)
     )
 
     mutually_exclusive = [


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

Issue:
fstab parameter of mount module won't work
##### Issue Type:
- Bug Report
##### Ansible Version:

ansible 2.0.0.2
  config file = /etc/ansible/ansible.cfg
  configured module search path = /usr/share/ansible
##### Ansible Configuration:
##### Environment:

Ubuntu 14.04 64Bit
##### Summary:

set fstab=**/tmp/fstab** in mount module result in 'can't find mount point in **/etc/fstab**'
##### Steps To Reproduce:

```
./test-module -m ../lib/ansible/modules/core/system/mount.py -a "src=/dev/sda9 name=/tmp/mnt fstype=ext3 state=mounted **fstab=/tmp/fstab**"
```
##### Expected Results:

```
changed: ok
```

and a line in /tmp/fstab and 'mount -a' should show the mounted device
##### Actual Results:

```
***********************************
PARSED OUTPUT
{
    "failed": true, 
    "invocation": {
        "module_args": {
            "dump": null, 
            "fstab": **"/tmp/fstab"**, 
            "fstype": "ext3", 
            "name": "/tmp/mnt", 
            "opts": null, 
            "passno": null, 
            "src": "/dev/sda9", 
            "state": "mounted"
        }
    }, 
    "msg": "Error mounting /tmp/mnt: mount: /tmp/mnt konnte nicht in **/etc/fstab oder /etc/mtab** gefunden werden\n"
}
```



Discussion:
Yep, it doesn't work on Linux, it seems to be only on freebsd for the current code. There is the option -T for Linux, could you give a try to the commit I propose ?

I tried your commit. I got an error like "no Option -T for mount". I looked into the manpage of mount and couldn't find -T on my Ubuntu 14.04 system.

Ok so that's only for newer coreutils. I guess we can add that to the doc and maybe some code to verify that, but I do not see any good way.

Looks like the fstab option is only applied on freebsd, so needs docs updated.

@grossws, ping. This issue is still waiting on your response.
[click here for bot help](https://github.com/jctanner/ansibullbot/blob/ISSUE_TRIAGE_CLASS/ISSUE_HELP.md)

<!--- boilerplate: issue_renotify_maintainer --->

This change appears to break mount tasks on RHEL6 / CentOS6.

Error mounting < /Some/Path > : /bin/mount: invalid option -- 'T'

Indeed, can you open a new issue, I will work on a fix.


Resolving patch:
diff --git a/system/mount.py b/system/mount.py
--- a/system/mount.py
+++ b/system/mount.py
@@ -375,7 +375,7 @@ def mount(module, **kwargs):
 
     if get_platform().lower() == 'freebsd':
         cmd += ['-F', args['fstab']]
-    elif get_platform().lower() == 'linux':
+    elif get_platform().lower() == 'linux' and args['fstab'] != '/etc/fstab':
         cmd += ['-T', args['fstab']]
 
     cmd += [name]


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

Issue:
ini_file module doesn't match existing key when it is indented
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

`ini_file` module
##### ANSIBLE VERSION

<!--- Paste verbatim output from “ansible --version” between quotes below -->

```
ansible 2.1.1.0
```
##### CONFIGURATION

N/A
##### OS / ENVIRONMENT

N/A
##### SUMMARY

When a key in an INI file exists but is prefixed with whitespace, the `ini_file` module adds a new entry rather than updating the existing entry.
##### STEPS TO REPRODUCE

Playbook:

```
- hosts: localhost
  gather_facts: no
  tasks:
    - ini_file:
        dest: ./foo.ini
        section: main
        option: foo
        value: baz
```

INI file:

```
[main]
  foo = bar
```
##### EXPECTED RESULTS

```
[main]
  foo = baz
```
##### ACTUAL RESULTS

```
[main]
  foo = bar
foo = baz
```



Discussion:
As an additional note, specifying the key with whitespace in the playbook _does_ work, but that's not really a good option.

```
option: "  foo"
```

@jpmens, @noseka1, ping. This issue is waiting on your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_notify_maintainer --->


Resolving patch:
diff --git a/files/ini_file.py b/files/ini_file.py
--- a/files/ini_file.py
+++ b/files/ini_file.py
@@ -109,7 +109,7 @@
 
 def match_opt(option, line):
   option = re.escape(option)
-  return re.match('%s( |\t)*=' % option, line) \
+  return re.match(' *%s( |\t)*=' % option, line) \
     or re.match('# *%s( |\t)*=' % option, line) \
     or re.match('; *%s( |\t)*=' % option, line)
 
@@ -118,7 +118,7 @@ def match_opt(option, line):
 
 def match_active_opt(option, line):
   option = re.escape(option)
-  return re.match('%s( |\t)*=' % option, line)
+  return re.match(' *%s( |\t)*=' % option, line)
 
 # ==============================================================
 # do_ini


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

Issue:
Failed AMI creation makes AMI run until timeout
##### ISSUE TYPE

<!--- Pick one below and delete the rest: -->
- Bug Report
##### COMPONENT NAME

ec2_ami
##### ANSIBLE VERSION

```
2.1
```
##### SUMMARY

Though rare an AMI creation can fail, returning a status of `failed`. The code doesn't check for this case, and keeps waiting until the timeout is expired. 
##### EXPECTED RESULTS

ec2_ami should return when a state of `failed` is encountered
##### ACTUAL RESULTS

ec2_ami does not return when a state of `failed` is encountered



Discussion:
Swamped at work but will toss up a PR shortly. 

@jjshoe, ping. This issue is still waiting on your response.
[click here for bot help](https://github.com/jctanner/ansibullbot/blob/ISSUE_TRIAGE_CLASS/ISSUE_HELP.md)

<!--- boilerplate: issue_renotify_maintainer --->

@jjshoe, ping. This issue is still waiting on your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_renotify_maintainer --->


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
@@ -395,6 +395,8 @@ def create_image(module, ec2):
 
             if img.state == 'available':
                 break
+            elif img.state == 'failed':
+                module.fail_json(msg="AMI creation failed, please see the AWS console for more details")
         except boto.exception.EC2ResponseError as e:
             if ('InvalidAMIID.NotFound' not in e.error_code and 'InvalidAMIID.Unavailable' not in e.error_code) and wait and i == wait_timeout - 1:
                 module.fail_json(msg="Error while trying to find the new image. Using wait=yes and/or a longer wait_timeout may help. %s: %s" % (e.error_code, e.error_message))


Test patch: