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

Issue:
Setup fails with "TimeoutError" on machines with floppy drive
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME

lib/ansible/module_utils/facts.py
setup module

##### ANSIBLE VERSION
```
ansible 2.2.0.0
```
Also devel

##### CONFIGURATION
default

##### OS / ENVIRONMENT
OpenSuSE 42.1 Leap

##### SUMMARY
Running the setup module of ansible 2.2.0.0 on a machine with a floppy drive fails with a timeout.

##### STEPS TO REPRODUCE

```
ansible oldmachine -m setup
```

##### EXPECTED RESULTS
Normal setup result

##### ACTUAL RESULTS
```
oldmachine | FAILED! => {
    "changed": false, 
    "cmd": "/usr/bin/lsblk --list --noheadings --paths --output NAME,UUID", 
    "failed": true, 
    "msg": "Timer expired", 
    "rc": 257
}
```

The issue was introduced by #17036.
`lsblk` is called once to collect all devices. For machines that still have floppy drives attached (don't laugh, those still exist), this includes floppy drives, which take very long to answer.

In our case it takes 12 seconds for the floppy drive, 0.1 seconds for everything else.


Discussion:

Resolving patch:
diff --git a/lib/ansible/module_utils/facts.py b/lib/ansible/module_utils/facts.py
--- a/lib/ansible/module_utils/facts.py
+++ b/lib/ansible/module_utils/facts.py
@@ -1228,7 +1228,11 @@ def get_dmi_facts(self):
                     self.facts[k] = 'NA'
 
     def _run_lsblk(self, lsblk_path):
-        args = ['--list', '--noheadings', '--paths',  '--output', 'NAME,UUID']
+        # call lsblk and collect all uuids
+        # --exclude 2 makes lsblk ignore floppy disks, which are slower to answer than typical timeouts
+        # this uses the linux major device number
+        # for details see https://www.kernel.org/doc/Documentation/devices.txt
+        args = ['--list', '--noheadings', '--paths',  '--output', 'NAME,UUID', '--exclude', '2']
         cmd = [lsblk_path] + args
         rc, out, err = self.module.run_command(cmd)
         return rc, out, err


Test patch:
Repository: ansible/ansible

Issue:
Add strategy modification to cli
##### Issue Type:
- Feature Idea
##### Ansible Version:

```
ansible --version
ansible 2.0.1.0
  config file = 
  configured module search path = Default w/o overrides
```
##### Ansible Configuration:

None
##### Environment:

OS X El Capitan
##### Summary:

Allow strategy to be modified by a cli flag. This will help editing playbook files to change the strategy of a run.
##### Steps To Reproduce:

```
ansible-playbook play.yml --strategy linear|free|serial
```
##### Expected Results:

Run using a specific strategy



Discussion:
Hi,

I need this feature. Is there any plan for it ? Is it ok if I provide a PR ?


Resolving patch:
diff --git a/lib/ansible/constants.py b/lib/ansible/constants.py
--- a/lib/ansible/constants.py
+++ b/lib/ansible/constants.py
@@ -268,6 +268,7 @@ def load_config_file():
 DEFAULT_FILTER_PLUGIN_PATH     = get_config(p, DEFAULTS, 'filter_plugins',     'ANSIBLE_FILTER_PLUGINS', '~/.ansible/plugins/filter:/usr/share/ansible/plugins/filter', value_type='pathlist')
 DEFAULT_TEST_PLUGIN_PATH       = get_config(p, DEFAULTS, 'test_plugins',       'ANSIBLE_TEST_PLUGINS', '~/.ansible/plugins/test:/usr/share/ansible/plugins/test', value_type='pathlist')
 DEFAULT_STRATEGY_PLUGIN_PATH   = get_config(p, DEFAULTS, 'strategy_plugins',   'ANSIBLE_STRATEGY_PLUGINS', '~/.ansible/plugins/strategy:/usr/share/ansible/plugins/strategy', value_type='pathlist')
+DEFAULT_STRATEGY               = get_config(p, DEFAULTS, 'strategy',           'ANSIBLE_STRATEGY', 'linear')
 DEFAULT_STDOUT_CALLBACK        = get_config(p, DEFAULTS, 'stdout_callback',    'ANSIBLE_STDOUT_CALLBACK', 'default')
 # cache
 CACHE_PLUGIN                   = get_config(p, DEFAULTS, 'fact_caching', 'ANSIBLE_CACHE_PLUGIN', 'memory')
diff --git a/lib/ansible/playbook/play.py b/lib/ansible/playbook/play.py
--- a/lib/ansible/playbook/play.py
+++ b/lib/ansible/playbook/play.py
@@ -20,6 +20,7 @@
 __metaclass__ = type
 
 from ansible.compat.six import string_types
+from ansible import constants as C
 
 from ansible.errors import AnsibleParserError
 
@@ -88,7 +89,7 @@ class Play(Base, Taggable, Become):
     _force_handlers      = FieldAttribute(isa='bool', always_post_validate=True)
     _max_fail_percentage = FieldAttribute(isa='percent', always_post_validate=True)
     _serial              = FieldAttribute(isa='list', default=[], always_post_validate=True)
-    _strategy            = FieldAttribute(isa='string', default='linear', always_post_validate=True)
+    _strategy            = FieldAttribute(isa='string', default=C.DEFAULT_STRATEGY, always_post_validate=True)
 
     # =================================================================================
 


Test patch:
Repository: ansible/ansible

Issue:
facts.py: global name 'to_text' is not defined
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
facts.py

##### ANSIBLE VERSION
```
ansible 2.3.0 (devel 527d8307c1) last updated 2016/11/12 10:15:49 (GMT +200)
  lib/ansible/modules/core: (detached HEAD 8d1fe3b444) last updated 2016/11/12 10:16:23 (GMT +200)
  lib/ansible/modules/extras: (detached HEAD 88e58df86b) last updated 2016/11/12 10:16:24 (GMT +200)
  config file = 
  configured module search path = Default w/o overrides
```

##### OS / ENVIRONMENT
OpenBSD -current

##### SUMMARY
Running the setup module fails, pointing to problem in facts.py.

##### STEPS TO REPRODUCE
```
$ ansible localhost -m setup 
 [WARNING]: Host file not found: /etc/ansible/hosts

 [WARNING]: provided hosts list is empty, only localhost is available

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: global name 'to_text' is not defined
localhost | FAILED! => {
    "changed": false, 
    "failed": true, 
    "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_f0Qygf/ansible_module_setup.py\", line 134, in <module>\n    main()\n  File \"/tmp/ansible_f0Qygf/ansible_module_setup.py\", line 126, in main\n    data = get_all_facts(module)\n  File \"/tmp/ansible_f0Qygf/ansible_modlib.zip/ansible/module_utils/facts.py\", line 3715, in get_all_facts\n  File \"/tmp/ansible_f0Qygf/ansible_modlib.zip/ansible/module_utils/facts.py\", line 3658, in ansible_facts\n  File \"/tmp/ansible_f0Qygf/ansible_modlib.zip/ansible/module_utils/facts.py\", line 1613, in populate\n  File \"/tmp/ansible_f0Qygf/ansible_modlib.zip/ansible/module_utils/facts.py\", line 1652, in get_memory_facts\nNameError: global name 'to_text' is not defined\n", 
    "module_stdout": "", 
    "msg": "MODULE FAILURE"
}
```

##### EXPECTED RESULTS
Collected facts shown on screen.

##### ACTUAL RESULTS
Error in facts.py.



Discussion:

Resolving patch:
diff --git a/lib/ansible/module_utils/facts.py b/lib/ansible/module_utils/facts.py
--- a/lib/ansible/module_utils/facts.py
+++ b/lib/ansible/module_utils/facts.py
@@ -35,7 +35,7 @@
 from ansible.module_utils.basic import get_all_subclasses
 from ansible.module_utils.six import PY3, iteritems
 from ansible.module_utils.six.moves import configparser, StringIO
-from ansible.module_utils._text import to_native
+from ansible.module_utils._text import to_native, to_text
 
 try:
     import selinux


Test patch:
Repository: ansible/ansible

Issue:
include_role loop fails when there are no items in the list
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
Linear strategy plugin

##### ANSIBLE VERSION
```
ansible 2.2.0.0
```

##### CONFIGURATION
N/A

##### OS / ENVIRONMENT
N/A

##### SUMMARY
When running `include_role` in a loop, an exception is thrown if the items list is empty:
```
ERROR! Unexpected Exception: 'results'
```

##### STEPS TO REPRODUCE
```
- hosts: localhost
  tasks:
  - include_role: name=anything
    with_items: []
```

##### EXPECTED RESULTS
The `include_role` task is not executed and the following output is produced:
```
TASK [include_role] ************************************************************
```

##### ACTUAL RESULTS
The play fails with an exception
```
TASK [include_role] ************************************************************
ERROR! Unexpected Exception: 'results'
the full traceback was:

Traceback (most recent call last):
  File "/usr/local/bin/ansible-playbook", line 103, in <module>
    exit_code = cli.run()
  File "/usr/local/Cellar/ansible/2.2.0.0_1/libexec/lib/python2.7/site-packages/ansible/cli/playbook.py", line 159, in run
    results = pbex.run()
  File "/usr/local/Cellar/ansible/2.2.0.0_1/libexec/lib/python2.7/site-packages/ansible/executor/playbook_executor.py", line 154, in run
    result = self._tqm.run(play=play)
  File "/usr/local/Cellar/ansible/2.2.0.0_1/libexec/lib/python2.7/site-packages/ansible/executor/task_queue_manager.py", line 282, in run
    play_return = strategy.run(iterator, play_context)
  File "/usr/local/Cellar/ansible/2.2.0.0_1/libexec/lib/python2.7/site-packages/ansible/plugins/strategy/linear.py", line 290, in run
    include_results = hr._result['results']
KeyError: 'results'
```

##### ROOT CAUSE
The value of `hr._result` is
```
{'skipped_reason': u'No items in the list', 'skipped': True, 'changed': False}
```
When the linear strategy tries to get the `results` key from the dict ([here](https://github.com/ansible/ansible/blob/99220a5f6cd2dd5af2903dce8cefeeb5ceaddf8f/lib/ansible/plugins/strategy/linear.py#L290)) it throws a `KeyError`.


Discussion:

Resolving patch:
diff --git a/lib/ansible/plugins/strategy/linear.py b/lib/ansible/plugins/strategy/linear.py
--- a/lib/ansible/plugins/strategy/linear.py
+++ b/lib/ansible/plugins/strategy/linear.py
@@ -287,7 +287,7 @@ def run(self, iterator, play_context):
                             loop_var = 'item'
                             if hr._task.loop_control:
                                 loop_var = hr._task.loop_control.loop_var or 'item'
-                            include_results = hr._result['results']
+                            include_results = hr._result.get('results', [])
                         else:
                             include_results = [ hr._result ]
 


Test patch:
Repository: ansible/ansible

Issue:
Git module fails to add hostkey to known_hosts and doesn't notice it
##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME

ansible.module_utils.known_hosts

##### ANSIBLE VERSION
```
ansible 2.1.3.0
  config file = 
  configured module search path = Default w/o overrides
```

##### OS / ENVIRONMENT

Ubuntu 16.04 

##### SUMMARY

Function add_host_key which gets called from  add_git_host_key, which gets called from the git module when accept_hostkey=yes, does not check that the output from ssh-keyscan is not empty. But ssh-keyscan has a timeout (5 seconds by default), and if the server could not answer in a timely manner, ssh-keyscan prints nothing to stdout and returns with return code 0. Ansible assumes that this operation is successful and proceeds to call git, which then hangs on a host key confirmation dialog.

The demonstration is as follows (I used -T1 to reproduce more easily, with default timeout of 5 seconds this also happens)
```
~$ ssh-keyscan -t rsa -T 1  bitbucket.org // this is succesful
# bitbucket.org:22 SSH-2.0-conker_1.0.263-aeae7ee app-134
bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==
~$ echo $? // ret code zero
0
~$ ssh-keyscan -t rsa -T 1  bitbucket.org // this one failed
~$ echo $? // ret code still zero
0
```

##### STEPS TO REPRODUCE

Execute a git task with a slow git server with accept_hostkey=yes

##### EXPECTED RESULTS

Fail with a meaningful error specifying that the keyscan was unsuccessful. Also, a way to increase the default timeout would be nice.

##### ACTUAL RESULTS

The module hangs indefinitely

related issue: https://github.com/ansible/ansible-modules-core/issues/1343



Discussion:

Resolving patch:
diff --git a/lib/ansible/module_utils/known_hosts.py b/lib/ansible/module_utils/known_hosts.py
--- a/lib/ansible/module_utils/known_hosts.py
+++ b/lib/ansible/module_utils/known_hosts.py
@@ -187,6 +187,9 @@ def add_host_key(module, fqdn, key_type="rsa", create_dir=False):
     this_cmd = "%s -t %s %s" % (keyscan_cmd, key_type, fqdn)
 
     rc, out, err = module.run_command(this_cmd)
+    # ssh-keyscan gives a 0 exit code and prints nothins on timeout
+    if rc != 0 or not out:
+        module.fail_json(msg='failed to get the hostkey for %s' % fqdn)
     module.append_to_file(user_host_file, out)
 
     return rc, out, err


Test patch:
Repository: ansible/ansible

Issue:
synchronize unnecessary fails to run when using docker connection
##### ISSUE TYPE
- Bug Report
##### ANSIBLE VERSION

```
ansible --version
ansible 2.1.0.0
  config file = /home/rossmohax/.ansible.cfg
  configured module search path = Default w/o overrides
```
##### OS / ENVIRONMENT

Linux
##### SUMMARY

synchronize unnecessary fails to run when using docker connection with an error:

```
{"changed": false, "failed": true, "msg": "synchronize uses rsync to function. rsync needs to connect to the remote host via ssh or a direct filesystem copy. This remote host is being accessed via docker instead so it cannot work."}
```

Which is simply wrong, here is the prove:
Copy into docker container without ssh:

```
rsync -a --rsh='docker exec -i' /tmp/myfiles c65e6a210eb:/tmp/
```

Copy from docker container without ssh:

```
rsync -a --rsh='docker exec -i' c65e6a210eb:/tmp/ /tmp/myfiles
```

where `c65e6a210eb` is a value used in inventory:

```
[targets]
container connection=docker ansible_host=c65e6a210eb
```



Discussion:
nice solution, +1 for somehow adding synchronize support

https://github.com/ansible/ansible/blob/4ea5f77062f427387d8c0486551e64e38072a8eb/lib/ansible/plugins/action/synchronize.py#L172-L177

@redbaron and @tomsun: Thanks for pointing this out. Please file a PR against this issue with your fix.

As this is not yet implemented, I am marking it as a feature idea.

Ping @chouseknecht in case maybe you have an idea for this.

It's on the list of things to do over at [ansible/ansible-container](https://github.com/ansible/ansible-container/issues/226)


Resolving patch:
diff --git a/lib/ansible/plugins/action/synchronize.py b/lib/ansible/plugins/action/synchronize.py
--- a/lib/ansible/plugins/action/synchronize.py
+++ b/lib/ansible/plugins/action/synchronize.py
@@ -354,7 +354,10 @@ def run(self, tmp=None, task_vars=None):
         # If launching synchronize against docker container
         # use rsync_opts to support container to override rsh options
         if self._remote_transport in [ 'docker' ]:
-            self._task.args['rsync_opts'] = "--rsh='%s exec -u %s -i'" % (self._docker_cmd, user)
+            if user is not None:
+                self._task.args['rsync_opts'] = "--rsh='%s exec -u %s -i'" % (self._docker_cmd, user)
+            else:
+                self._task.args['rsync_opts'] = "--rsh='%s exec -i'" % (self._docker_cmd)
 
         # run the module and store the result
         result.update(self._execute_module('synchronize', task_vars=task_vars))


Test patch:
Repository: ansible/ansible

Issue:
Ensure non-root users can read arguments file when using sudo_user and non-standard modules
Non-standard modules must read in the arguments file in order to access their arguments, however, when this file is transfered to the remote host it may only have the permissions 600.  This means that using sudo and sudo_user will result in permission denied errors when attempting to read the arguments file.

This patch fixes #4438 by explicitly forcing the arguments file to be world readable before executing the module.



Discussion:
Fixes #4438

merged, thanks!


Resolving patch:
diff --git a/lib/ansible/modules/cloud/amazon/ecs_taskdefinition.py b/lib/ansible/modules/cloud/amazon/ecs_taskdefinition.py
--- a/lib/ansible/modules/cloud/amazon/ecs_taskdefinition.py
+++ b/lib/ansible/modules/cloud/amazon/ecs_taskdefinition.py
@@ -48,7 +48,7 @@
         type: int
     containers:
         description:
-            - A list of containers definitions 
+            - A list of containers definitions
         required: False
         type: list of dicts with container definitions
     volumes:
@@ -138,8 +138,24 @@ def describe_task(self, task_name):
             return None
 
     def register_task(self, family, container_definitions, volumes):
+        validated_containers = []
+
+        # Ensures the number parameters are int as required by boto
+        for container in container_definitions:
+            for param in ('memory', 'cpu', 'memoryReservation'):
+                if param in container:
+                    container[param] = int(container[param])
+
+            if 'portMappings' in container:
+                for port_mapping in container['portMappings']:
+                    for port in ('hostPort', 'containerPort'):
+                        if port in port_mapping:
+                            port_mapping[port] = int(port_mapping[port])
+
+            validated_containers.append(container)
+
         response = self.ecs.register_task_definition(family=family,
-            containerDefinitions=container_definitions, volumes=volumes)
+            containerDefinitions=validated_containers, volumes=volumes)
         return response['taskDefinition']
 
     def describe_task_definitions(self, family):


Test patch:
Repository: ansible/ansible

Issue:
Fix inventory parsing so that FQDN can be parsed without throwing ssh port error
We use two ranges to define our hosts, first for the bladecenter, then the blade slot, so we have hosts defined like this:

```
[servers]
host-[1:6]-[1:16].example.com
```

gives (Line numbers might be slightly out due to due to extra debugging I've added)

``` python
File "/mnt/data/home/johnb/development/ansible/mine/lib/ansible/inventory/host.py", line 31, in __init__
    self.set_variable('ansible_ssh_port', int(port))
ValueError: invalid literal for int() with base 10: 'com:2222'
```

I believe this is a regression over 1.3.4, possibly caused by https://github.com/ansible/ansible/commit/948d019fef8781b22960859caaa93485a074e339

Added unit tests for FQDN. I couldn't see any existing ones. They could be extended further, but at least this particular issues is fixed and defended

Fix inventory parsing so that FQDN can be parsed without throwing ssh port error
We use two ranges to define our hosts, first for the bladecenter, then the blade slot, so we have hosts defined like this:

```
[servers]
host-[1:6]-[1:16].example.com
```

gives (Line numbers might be slightly out due to due to extra debugging I've added)

``` python
File "/mnt/data/home/johnb/development/ansible/mine/lib/ansible/inventory/host.py", line 31, in __init__
    self.set_variable('ansible_ssh_port', int(port))
ValueError: invalid literal for int() with base 10: 'com:2222'
```

I believe this is a regression over 1.3.4, possibly caused by https://github.com/ansible/ansible/commit/948d019fef8781b22960859caaa93485a074e339

Added unit tests for FQDN. I couldn't see any existing ones. They could be extended further, but at least this particular issues is fixed and defended



Discussion:
@bob-smith thank you!

@bob-smith thank you!


Resolving patch:
diff --git a/lib/ansible/modules/cloud/docker/docker_container.py b/lib/ansible/modules/cloud/docker/docker_container.py
--- a/lib/ansible/modules/cloud/docker/docker_container.py
+++ b/lib/ansible/modules/cloud/docker/docker_container.py
@@ -207,6 +207,7 @@
     description:
       - Specify the logging driver. Docker uses json-file by default.
     choices:
+      - none
       - json-file
       - syslog
       - journald
@@ -1958,7 +1959,9 @@ def main():
         kill_signal=dict(type='str'),
         labels=dict(type='dict'),
         links=dict(type='list'),
-        log_driver=dict(type='str', choices=['json-file', 'syslog', 'journald', 'gelf', 'fluentd', 'awslogs', 'splunk'], default=None),
+        log_driver=dict(type='str',
+                        choices=['none', 'json-file', 'syslog', 'journald', 'gelf', 'fluentd', 'awslogs', 'splunk'],
+                        default=None),
         log_options=dict(type='dict', aliases=['log_opt']),
         mac_address=dict(type='str'),
         memory=dict(type='str', default='0'),


Test patch:
Repository: ansible/ansible

Issue:
Conditional includes and registered variables not evaluating correctly
There is an issue when a playbook is included based on a variable.  When the condition is not met, the playbook is "skipped".  However, "when" statements are still evaluated in the skipped playbook's tasks.  I have seen this behavior on the latest 1.2 release as well as the most recent 1.3 dev branch.

This is the 'main.yml' and playbook I am using:

main.yml:
- include: dbapp.yml
  when: "'{{ role }}' == 'dbapp'"
- include: webapp.yml
  when: "'{{ role }}' == 'webapp'"
- include: solr.yml
  when: "'{{ role }}' == 'SOLR'"

dbapp.yml:
- name: Check if tomcat 7 is installed
  stat: path=/opt/apache-tomcat-{{ tc_ver }}
  register: t7
- name: Fetch tomcat 7
  s3: >
    bucket=xxxxxxxx
    object=/tomcat/apache-tomcat-{{ tc_ver }}.tar.gz
    dest=/tmp/apache-tomcat-{{ tc_ver }}.tar.gz
    mode=get
    ec2_access_key={{ aws_creds.access_key }}
    ec2_secret_key={{ aws_creds.secret_key }}
  when: t7.stat.isdir is not defined
  ignore_errors: yes

I am using this command to call it with the results:

ansible-playbook -i host, -e "role='webapp'" profile_test.yml

Results:
PLAY [Configure instance(s) profiles] *****************************************

GATHERING FACTS ***************************************************************
ok: [xxxxxxxxxxxxxxx]

TASK: [Check if tomcat 7 is installed] ****************************************
skipping: [xxxxxxxxxxxxxxx]

TASK: [Fetch tomcat 7] ********************************************************
fatal: [xxxxxxxxxxxxxxx] => unable to evaluate conditional: {% if t7.stat.isdir is not defined %} True {% else %} False {% endif %}

FATAL: all hosts have already failed -- aborting

PLAY RECAP ********************************************************************
xxxxxxxxxxxxxxx : ok=1    changed=0    unreachable=1    failed=0



Discussion:
the include is not conditional.

the when gets applied to each task included.

This is normal and expected behavior. Internally, included playbooks are read and all of their tasks are added to the task list. When using a conditional modifier, that conditional is applied to all of those added tasks, which is the behavior you're seeing.


Resolving patch:
diff --git a/lib/ansible/modules/packaging/os/redhat_subscription.py b/lib/ansible/modules/packaging/os/redhat_subscription.py
--- a/lib/ansible/modules/packaging/os/redhat_subscription.py
+++ b/lib/ansible/modules/packaging/os/redhat_subscription.py
@@ -459,6 +459,8 @@ def filter(self, regexp='^$'):
         for product in self.products:
             if r.search(product._name):
                 yield product
+            if r.search(product.PoolID):
+                yield product
 
 
 def main():


Test patch: