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

Issue:
sysctl bug - yaml dict format in sysctl task with an int value reports 'changed=true' every run.  
Issue Type: Bug Report
Ansible Version:

```
~/vagrant/centos $ ansible --version
ansible 1.9.1
```

Ansible Configuration: default

Environment:
mac osx controller using vagrant centos image

```
[vagrant@localhost ~]$ cat /etc/centos-release 
CentOS release 6.6 (Final)
```

Summary:
Using the yaml dict format in sysctl task with an int value reports 'changed=true' every run.  

Steps To Reproduce:
- use the following vagrantfile

```
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.box = "chef/centos-6.6"

  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "play.yml"
  end 

end
```
- run the following playbook

```

---
- hosts: all 
  remote_user: vagrant
  sudo: true
  tasks:

    - yum: name=libselinux-python state=present
    - selinux: state=disabled

    - name: set vm swappiness
      sysctl:
        ignoreerrors: true
        name: vm.swappiness
        value: 10
      register: result

    - debug: var=result
```

e.g.

```
~/vagrant/centos $ ANSIBLE_KEEP_REMOTE_FILES=1 ansible-playbook play.yml -i hosts -vvvv --private-key=.vagrant/machines/default/virtualbox/private_key
```
- re-run the playbook

Expected Results:
After re-running, it should not change anything

```
TASK: [set vm swappiness] ***************************************************** 
ok: [default]
```

Actual Results:
It reports it as changed

```
TASK: [set vm swappiness] ***************************************************** 
changed: [default]
```

Debugging:
The module appears to parse the sysctl.conf file into a json dict, and all values are strings, when the module is passed an int value, it fails on the comparison.

Full debugging is here - https://gist.github.com/halberom/6bd0abcff79a50af529e



Discussion:
Additional thoughts...

The examples in the module docs are key=value parameters.  Which in yaml is essentially a string value, so those work.  Only in the yaml dict structure does this fail as a number is interpreted as an int value.

confirm that PR above fixes your issue


Resolving patch:
diff --git a/system/sysctl.py b/system/sysctl.py
--- a/system/sysctl.py
+++ b/system/sysctl.py
@@ -322,7 +322,7 @@ def main():
     module = AnsibleModule(
         argument_spec = dict(
             name = dict(aliases=['key'], required=True),
-            value = dict(aliases=['val'], required=False),
+            value = dict(aliases=['val'], required=False, type='str'),
             state = dict(default='present', choices=['present', 'absent']),
             reload = dict(default=True, type='bool'),
             sysctl_set = dict(default=False, type='bool'),


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

Issue:
mysql_user: check_implicit_admin vs documentation
Documentation says: 
"Both C(login_password) and C(login_username) are required when you are
     passing credentials. If none are present, the module will attempt to read
     the credentials from C(~/.my.cnf), and finally fall back to using the MySQL
     default login of 'root' with no password."

However this is only true if the option "check_implicit_admin" is used, otherwise the last resort of "root" + no password is never reached.

This might have been intended, but please update docs.



Discussion:
While looking at this I found that the check_implicit_admin value, which is treated as a boolean, is not typed or documented as one.

argument_spec() entry:

```
check_implicit_admin=dict(default=False)
```

what I think we want:

```
check_implicit_admin=dict(type="bool",  default="no")
```

Either way I suggest the _Options_ section be updated with a _choices_ entry as well as updating the _Note_ ( let me know )

I have a PR for the documentation update ready to go, but then I tripped over the argument type change.  Since this issue is flagged for documentation I wasn't sure what the policy was for making non-doc changes in a documentation Issue.  If you prefer I can open another Issue against the code change and create a second PR.


Resolving patch:
diff --git a/database/mysql/mysql_user.py b/database/mysql/mysql_user.py
--- a/database/mysql/mysql_user.py
+++ b/database/mysql/mysql_user.py
@@ -90,7 +90,8 @@
     description:
       - Check if mysql allows login as root/nopassword before trying supplied credentials.
     required: false
-    default: false
+    choices: [ "yes", "no" ]
+    default: "no"
     version_added: "1.3"
   update_password:
     required: false
@@ -385,8 +386,8 @@ def main():
             host=dict(default="localhost"),
             state=dict(default="present", choices=["absent", "present"]),
             priv=dict(default=None),
-            append_privs=dict(type="bool", default="no"),
-            check_implicit_admin=dict(default=False),
+            append_privs=dict(default=False, type='bool'),
+            check_implicit_admin=dict(default=False, type='bool'),
             update_password=dict(default="always", choices=["always", "on_create"]),
             config_file=dict(default="~/.my.cnf"),
         )


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

Issue:
Mount module "state: unmounted" should not require src and fstype arguments
When wanting to ensure a particular path has nothing mounted on it, I would like to be able to do:

```
- name: "Ensure chroot paths are not mounted"
  mount:
    name: "{{ item }}"
    state: unmounted
  with_items:
    - var/cache/apt
    - dev
    - proc
    - sys
```

But Ansible throws this error:

```
failed: [testhost] => (item=proc) => {"failed": true, "item": "proc"}
msg: missing required arguments: src,fstype
```

I believe when making sure a path is not mounted, the arguments src and fstype should be optional.



Discussion:
The same could hold true for _absent_ ( remove from fstab only ).  _src_ and _fstype_ aren't used for either action.  We would have to remove the required flags and add explicit checks for those values for _present_ and _mounted_.

Since neither of those values are evaluated on _unmount_, as a work around you could give them bogus values.

`mount: name={{ item }} state=unmounted src=none fstype=none`


Resolving patch:
diff --git a/system/mount.py b/system/mount.py
--- a/system/mount.py
+++ b/system/mount.py
@@ -34,12 +34,14 @@
     required: true
   src:
     description:
-      - device to be mounted on I(name).
-    required: true
+        - device to be mounted on I(name). Required when C(state=present) or C(state=mounted)
+    required: false
+    default: null
   fstype:
     description:
-      - file-system type
-    required: true
+      - file-system type. Required when C(state=present) or C(state=mounted)
+    required: false
+    default: null
   opts:
     description:
       - mount options (see fstab(5))
@@ -261,21 +263,25 @@ def main():
             opts   = dict(default=None),
             passno = dict(default=None, type='str'),
             dump   = dict(default=None),
-            src    = dict(required=True),
-            fstype = dict(required=True),
+            src    = dict(required=False),
+            fstype = dict(required=False),
             fstab  = dict(default='/etc/fstab')
         ),
-        supports_check_mode=True
+        supports_check_mode=True,
+        required_if = (
+            ['state', 'mounted', ['src', 'fstype']],
+            ['state', 'present', ['src', 'fstype']]
+        )
     )
 
 
     changed = False
     rc = 0
-    args = {
-        'name': module.params['name'],
-        'src': module.params['src'],
-        'fstype': module.params['fstype']
-    }
+    args = {'name': module.params['name']}
+    if module.params['src'] is not None:
+        args['src'] = module.params['src']
+    if module.params['fstype'] is not None:
+        args['fstype'] = module.params['fstype']
     if module.params['passno'] is not None:
         args['passno'] = module.params['passno']
     if module.params['opts'] is not None:


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

Issue:
ec2 module cannot create encrypted volumes
While with the ec2_vol module encrypted volumes can be created, the 'built-in' volume specification in the ec2 module does not allow for it. The 'encrypted' attribute can be set, but it's ignored.

Example:

```
- ec2:
    instance_type: m3.medium
    image: ami-123456
    volumes:
      - device_name: /dev/sdb
        device_type: gp2
        volume_size: 100
        encrypted: true
```

However, the created volume will not be encrypted.

Fortunately, the fix is very straight forward:

In cloud/amazon/ec2.py, at the end of create_block_device() add this parameter to the "return BlockDeviceType(....) call:

```
...
encrypted=volume.get('encrypted', False),
....
```

I confirmed locally that this produces an encrypted volume.



Discussion:
+1

+1

+1


Resolving patch:
diff --git a/cloud/amazon/ec2.py b/cloud/amazon/ec2.py
--- a/cloud/amazon/ec2.py
+++ b/cloud/amazon/ec2.py
@@ -201,7 +201,7 @@
   volumes:
     version_added: "1.5"
     description:
-      - a list of volume dicts, each containing device name and optionally ephemeral id or snapshot id. Size and type (and number of iops for io device type) must be specified for a new volume or a root volume, and may be passed for a snapshot volume. For any volume, a volume size less than 1 will be interpreted as a request not to create the volume.
+      - a list of volume dicts, each containing device name and optionally ephemeral id or snapshot id. Size and type (and number of iops for io device type) must be specified for a new volume or a root volume, and may be passed for a snapshot volume. For any volume, a volume size less than 1 will be interpreted as a request not to create the volume. Encrypt the volume by passing 'encrypted: true' in the volume dict.
     required: false
     default: null
     aliases: []
@@ -672,7 +672,8 @@ def create_block_device(module, ec2, volume):
                            size=volume.get('volume_size'),
                            volume_type=volume.get('device_type'),
                            delete_on_termination=volume.get('delete_on_termination', False),
-                           iops=volume.get('iops'))
+                           iops=volume.get('iops'),
+                           encrypted=volume.get('encrypted', False))
 
 def boto_supports_param_in_spot_request(ec2, param):
     """


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

Issue:
vsphere_guest KeyError: 'memory_mb' on reconfigure
With no memory_mb key specified on a 'reconfigre' state where is a KeyError doing a check on the value.

```
- vsphere_guest:
      vcenter_hostname: "{{ vcenter_hostname }}"
      username: "{{ vcenter_user }}"
      password: "{{ vcenter_pass }}"
      guest: "{{ inventory_hostname }}"
      state: reconfigured
      vm_extra_config:
        notes: "{{ notes }}"
        hostname: "{{ inventory_hostname }}.mcp.com"
        mem.hotadd:  yes
    delegate_to: 127.0.0.1
```

```
Traceback (most recent call last):
  File "/home/test/.ansible/tmp/ansible-tmp-1433541575.35-260395156322519/vsphere_guest", line 2923, in <module>
    main()
  File "/home/test/.ansible/tmp/ansible-tmp-1433541575.35-260395156322519/vsphere_guest", line 1255, in main
    force=force
  File "/home/test/.ansible/tmp/ansible-tmp-1433541575.35-260395156322519/vsphere_guest", line 571, in reconfigure_vm
    if vm_hardware['memory_mb']:
KeyError: 'memory_mb'
```



Discussion:

Resolving patch:
diff --git a/cloud/vmware/vsphere_guest.py b/cloud/vmware/vsphere_guest.py
--- a/cloud/vmware/vsphere_guest.py
+++ b/cloud/vmware/vsphere_guest.py
@@ -577,7 +577,7 @@ def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name
     cpuHotRemoveEnabled = bool(vm.properties.config.cpuHotRemoveEnabled)
 
     # Change Memory
-    if vm_hardware['memory_mb']:
+    if 'memory_mb' in vm_hardware:
 
         if int(vm_hardware['memory_mb']) != vm.properties.config.hardware.memoryMB:
             spec = spec_singleton(spec, request, vm)
@@ -607,7 +607,7 @@ def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name
             changes['memory'] = vm_hardware['memory_mb']
 
     # ====( Config Memory )====#
-    if vm_hardware['num_cpus']:
+    if 'num_cpus' in vm_hardware:
         if int(vm_hardware['num_cpus']) != vm.properties.config.hardware.numCPU:
             spec = spec_singleton(spec, request, vm)
 


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

Issue:
vsphere_guest reconfigure powers on VM
Issue type: Bug Report

Ansible  Version:  ansible 1.9.1

Ansible Configuration: 

n/a

Environment: 
CentOS 6 -> ESX 5.0.0

Summary: 

Reconfiguring a VM also powers on a powered off VM.  

Steps to Reproduce: 

Running the following play:

```
  - name: change nic
    vsphere_guest:
      vcenter_hostname: {{ my_vc }}
      username: "{{ vc_user }}"
      password: "{{ vc_pw }}"
      guest: "{{ vm_hostname }}"
      state: reconfigured
      force: yes
      vm_nic:
        nic1:
          type: vmxnet3
          network_type: standard
          network: "VM Network"
      vm_hardware:
        memory_mb: 8192 # was 4096
        num_cpus: 2
      esxi:
        datacenter: "{{ my_dc }}"
        hostname: "{{ my_esxhost }}"
```

Expected behaviour: VM is reconfigured, but left powered off

Exhibited behaviour: VM is reconfigured but unexpectedly powers on! 



Discussion:
@bennojoy should this be implemented? eg. via a poweron key?

@vtsingaras  would it be possible to check the current state if the vm, before reconfiguring and just maintain that state after reconfiguration so that we dont have to add a new key ? 

Yes that's possible but note that during some operations(eg. memory add without hotadd support) the VM must be powered off for the reconfiguration task to succeed. We can however get its power state at the start of the task and use it at the end to decide on powerOn/powerOff. Does that sound OK?

@vtsingaras  sounds good, we can add it in docs that reconfigure can poweroff the vm in case of scenarios you mentioned above.


Resolving patch:
diff --git a/cloud/vmware/vsphere_guest.py b/cloud/vmware/vsphere_guest.py
--- a/cloud/vmware/vsphere_guest.py
+++ b/cloud/vmware/vsphere_guest.py
@@ -571,6 +571,7 @@ def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name
     changes = {}
     request = VI.ReconfigVM_TaskRequestMsg()
     shutdown = False
+    poweron = vm.is_powered_on()
 
     memoryHotAddEnabled = bool(vm.properties.config.memoryHotAddEnabled)
     cpuHotAddEnabled = bool(vm.properties.config.cpuHotAddEnabled)
@@ -661,7 +662,7 @@ def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name
             module.fail_json(
                 msg="Error reconfiguring vm: %s" % task.get_error_message())
 
-        if vm.is_powered_off():
+        if vm.is_powered_off() and poweron:
             try:
                 vm.power_on(sync_run=True)
             except Exception, e:


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

Issue:
unarchive: don't try to work on 0 byte files
When you call unarchive on an archive that's 0 bytes it will report "Failed to find handler to unarchive. Make sure the required command to extract the file is installed.", which is rather misleading.

A solution forward might be to check for 0 byte size before trying to work on the file.



Discussion:
Makes sense -- could be a straightforward PR if you have the time...

Yeah, will definitely do that as soon as I find a few free minutes at the office this week.

Thanks! Appreciate your time. :)


Resolving patch:
diff --git a/files/unarchive.py b/files/unarchive.py
--- a/files/unarchive.py
+++ b/files/unarchive.py
@@ -300,6 +300,13 @@ def main():
     if not os.access(src, os.R_OK):
         module.fail_json(msg="Source '%s' not readable" % src)
 
+    # skip working with 0 size archives
+    try:
+        if os.path.getsize(src) == 0:
+            module.fail_json(msg="Invalid archive '%s', the file is 0 bytes" % src)
+    except Exception, e:
+        module.fail_json(msg="Source '%s' not readable" % src)
+
     # is dest OK to receive tar file?
     if not os.path.isdir(dest):
         module.fail_json(msg="Destination '%s' is not a directory" % dest)


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

Issue:
Feature Request: config file validation in assemble module
##### Issue Type: Feature Request
##### Ansible Version:

```
ansible 1.8.2
  configured module search path = None
```
##### Environment:

up-to-date Archlinux (as of 2014-12-27)
##### Summary:

Ansible module _assemble_ does not currently support _validate_ attribute .
I think this might be nice feature to have, because if someone decides to split configuration file generation into multiple places, validation may become impossible.

 And having _validate_ would allow to perform this kind of check without putting separate task  after _assemble_ entry.
##### Steps To Reproduce:

N/A
##### Expected Results:

Possibility to validate file generated by assemble module
##### Actual Results:

Module currently does not support this operation 



Discussion:

Resolving patch:
diff --git a/files/assemble.py b/files/assemble.py
--- a/files/assemble.py
+++ b/files/assemble.py
@@ -85,6 +85,13 @@
     required: false
     default: false
     version_added: "2.0"
+  validate:
+    description:
+      - The validation command to run before copying into place.  The path to the file to
+        validate is passed in via '%s' which must be present as in the sshd example below.
+        The command is passed securely so shell features like expansion and pipes won't work.
+    required: false
+    default: ""
 author: "Stephen Fromm (@sfromm)"
 extends_documentation_fragment: files
 '''
@@ -95,6 +102,9 @@
 
 # When a delimiter is specified, it will be inserted in between each fragment
 - assemble: src=/etc/someapp/fragments dest=/etc/someapp/someapp.conf delimiter='### START FRAGMENT ###'
+
+# Copy a new "sshd_config" file into place, after passing validation with sshd
+- assemble: src=/etc/ssh/conf.d/ dest=/etc/ssh/sshd_config validate='sshd -t -f %s'
 '''
 
 # ===========================================
@@ -155,6 +165,7 @@ def main():
             remote_src=dict(default=False, type='bool'),
             regexp = dict(required=False),
             ignore_hidden = dict(default=False, type='bool'),
+            validate = dict(required=False, type='str'),
         ),
         add_file_common_args=True
     )
@@ -170,6 +181,7 @@ def main():
     regexp    = module.params['regexp']
     compiled_regexp = None
     ignore_hidden = module.params['ignore_hidden']
+    validate = module.params.get('validate', None)
 
     if not os.path.exists(src):
         module.fail_json(msg="Source (%s) does not exist" % src)
@@ -192,6 +204,13 @@ def main():
     if path_hash != dest_hash:
         if backup and dest_hash is not None:
             module.backup_local(dest)
+        if validate:
+            if "%s" not in validate:
+                module.fail_json(msg="validate must contain %%s: %s" % validate)
+            (rc, out, err) = module.run_command(validate % path)
+            if rc != 0:
+                module.fail_json(msg="failed to validate: rc:%s error:%s" % (rc, err))
+
         shutil.copy(path, dest)
         changed = True
 


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

Issue:
aws_key not honoring --check
The aws_key module is not honoring --check flag.

In my play I have:

```
- name: Remove aws keys
  local_action: ec2_key name=infra_{{ stack }} region={{ ec2_region }} state=absent
  ignore_errors: yes
  tags:
```

When I run the play with --check the key is actually being deleted!



Discussion:
he, the present has `if not module.check_mode:` but the absent does not


Resolving patch:
diff --git a/cloud/amazon/ec2_key.py b/cloud/amazon/ec2_key.py
--- a/cloud/amazon/ec2_key.py
+++ b/cloud/amazon/ec2_key.py
@@ -127,25 +127,23 @@ def main():
     if state == 'absent':
         if key:
             '''found a match, delete it'''
-            try:
-                key.delete()
-                if wait:
-                    start = time.time()
-                    action_complete = False
-                    while (time.time() - start) < wait_timeout:
-                        if not ec2.get_key_pair(name):
-                            action_complete = True
-                            break
-                        time.sleep(1)
-                    if not action_complete:
-                        module.fail_json(msg="timed out while waiting for the key to be removed")
-            except Exception, e:
-                module.fail_json(msg="Unable to delete key pair '%s' - %s" % (key, e))
-            else:
-                key = None
-                changed = True
-        else:
-            '''no match found, no changes required'''
+            if not module.check_mode:
+                try:
+                    key.delete()
+                    if wait:
+                        start = time.time()
+                        action_complete = False
+                        while (time.time() - start) < wait_timeout:
+                            if not ec2.get_key_pair(name):
+                                action_complete = True
+                                break
+                            time.sleep(1)
+                        if not action_complete:
+                            module.fail_json(msg="timed out while waiting for the key to be removed")
+                except Exception, e:
+                    module.fail_json(msg="Unable to delete key pair '%s' - %s" % (key, e))
+            key = None
+            changed = True
 
     # Ensure requested key is present
     elif state == 'present':


Test patch: