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

Issue:
Jail connection ignores sudo_user
##### Issue Type:

Bug Report
##### Ansible Version:

ansible 1.4.4 
##### Environment:

I am running FreeBSD 10.0-RELEASE and managing 10.0-RELEASE jails.
##### Summary:

The connection type “jail" ignores the sudo_user setting, commands are always executed as root. 

As the connection type uses jexec already, this can probably be fixed trivially by using jexec -U 
##### Steps To Reproduce:

```
# ansible putover -U mxey -a "id"
```
##### Expected Results:

```
# ansible putover -U mxey -a "id"                                                 :(
putover | success | rc=0 >>
uid=1001(mxey) gid=1001(mxey) groups=1001(mxey),0(wheel)
```
##### Actual Results:

```
 # ansible putover -U mxey -a "id"
putover | success | rc=0 >>
uid=0(root) gid=0(wheel) groups=0(wheel),5(operator)
```



Discussion:
Something you would like to help work on perhaps?

I am unsure if I should support sudo_user or remote_user with jexec, because it won't actually use the sudo command. 


Resolving patch:
diff --git a/lib/ansible/plugins/connection/jail.py b/lib/ansible/plugins/connection/jail.py
--- a/lib/ansible/plugins/connection/jail.py
+++ b/lib/ansible/plugins/connection/jail.py
@@ -94,7 +94,7 @@ def _connect(self):
         ''' connect to the jail; nothing to do here '''
         super(Connection, self)._connect()
         if not self._connected:
-            display.vvv("THIS IS A LOCAL JAIL DIR", host=self.jail)
+            display.vvv(u"ESTABLISH JAIL CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self.jail)
             self._connected = True
 
     def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
@@ -105,8 +105,16 @@ def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
         compared to exec_command() it looses some niceties like being able to
         return the process's exit code immediately.
         '''
-        executable = C.DEFAULT_EXECUTABLE.split()[0] if C.DEFAULT_EXECUTABLE else '/bin/sh'
-        local_cmd = [self.jexec_cmd, self.jail, executable, '-c', cmd]
+
+        local_cmd = [self.jexec_cmd]
+        set_env = ''
+
+        if self._play_context.remote_user is not None:
+            local_cmd += ['-U', self._play_context.remote_user]
+            # update HOME since -U does not update the jail environment
+            set_env = 'HOME=~' + self._play_context.remote_user + ' '
+
+        local_cmd += [self.jail, self._play_context.executable, '-c', set_env + cmd]
 
         display.vvv("EXEC %s" % (local_cmd,), host=self.jail)
         local_cmd = [to_bytes(i, errors='strict') for i in local_cmd]


Test patch:
Repository: ansible/ansible

Issue:
retry_files_save_path directory is not created when missing
##### Issue Type:
- Bug Report
##### Ansible Version:

```
ansible 2.0.1.0
```
##### Ansible Configuration:

```
[defaults]
retry_files_save_path = .ansible-retry
```
##### Environment:

Ubuntu 14.04
##### Summary:

http://docs.ansible.com/ansible/intro_configuration.html#retry-files-save-path says about `retry_files_save_path`:

> The directory will be created if it does not already exist.

That doesn't seem to work.
##### Steps To Reproduce:

Set `retry_files_save_path = .ansible-retry` in your `ansible.cfg`, without creating the directory `.ansible-retry`.

Run a playbook that fails. You'll get the error:

```
NO MORE HOSTS LEFT *************************************************************
 [ERROR]: Could not create retry file '.ansible-retry/myplaybook.retry'. The error was: [Errno 2] No
such file or directory: '.ansible-retry/myplaybook.retry'
```

Then `mkdir .ansible-retry`, run again, the error is gone.
##### Expected Results:

Ansible should create the directory, as stated in the documentation.



Discussion:

Resolving patch:
diff --git a/lib/ansible/executor/playbook_executor.py b/lib/ansible/executor/playbook_executor.py
--- a/lib/ansible/executor/playbook_executor.py
+++ b/lib/ansible/executor/playbook_executor.py
@@ -27,6 +27,7 @@
 from ansible.executor.task_queue_manager import TaskQueueManager
 from ansible.playbook import Playbook
 from ansible.template import Templar
+from ansible.utils.path import makedirs_safe
 from ansible.utils.unicode import to_unicode
 
 try:
@@ -247,6 +248,7 @@ def _generate_retry_inventory(self, retry_path, replay_hosts):
         re-running on ONLY the failed hosts.  This may duplicate some variable
         information in group_vars/host_vars but that is ok, and expected.
         '''
+        makedirs_safe(os.path.dirname(retry_path))
 
         try:
             with open(retry_path, 'w') as fd:


Test patch:
Repository: ansible/ansible

Issue:
- meta: refresh_inventory causes playbook to exit. 
##### ISSUE TYPE
- Bug Report
##### ANSIBLE VERSION

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

pipelining=True
Custom dynamic inventory
##### OS / ENVIRONMENT

$ uname -a
Linux will 4.2.0-23-generic #28-Ubuntu SMP Sun Dec 27 17:47:31 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
##### SUMMARY

After calling - meta: refresh_inventory the playbook exits
##### STEPS TO REPRODUCE

Run the following:

```

---
- hosts: test_host
  remote_user: root


  tasks:

    - debug: msg='before refresh'

    - meta: refresh_inventory

    - debug: msg='after refresh'
```
##### EXPECTED RESULTS

The message "after refresh" to be printed after the inventory was refreshed. 
##### ACTUAL RESULTS

Playbook exits. 

The inventory is called a second time though. 

```
$ ansible-playbook refresh_inv.yml 

PLAY [ansible.test.au.seqta.vpn] ***********************************************

TASK [setup] *******************************************************************
ok: [ansible.test.au.seqta.vpn]

TASK [debug] *******************************************************************
ok: [ansible.test.au.seqta.vpn] => {
    "msg": "before refresh"
}

PLAY RECAP *********************************************************************
ansible.test.au.seqta.vpn  : ok=2    changed=0    unreachable=0    failed=0   

```



Discussion:

Resolving patch:
diff --git a/lib/ansible/inventory/__init__.py b/lib/ansible/inventory/__init__.py
--- a/lib/ansible/inventory/__init__.py
+++ b/lib/ansible/inventory/__init__.py
@@ -204,7 +204,7 @@ def get_hosts(self, pattern="all", ignore_limits_and_restrictions=False):
 
                 # exclude hosts mentioned in any restriction (ex: failed hosts)
                 if self._restriction is not None:
-                    hosts = [ h for h in hosts if h in self._restriction ]
+                    hosts = [ h for h in hosts if h.name in self._restriction ]
 
             seen = set()
             HOSTS_PATTERNS_CACHE[pattern_hash] = [x for x in hosts if x not in seen and not seen.add(x)]
@@ -600,7 +600,7 @@ def restrict_to_hosts(self, restriction):
             return
         elif not isinstance(restriction, list):
             restriction = [ restriction ]
-        self._restriction = restriction
+        self._restriction = [ h.name for h in restriction ]
 
     def subset(self, subset_pattern):
         """ 


Test patch:
Repository: ansible/ansible

Issue:
Module loader doesn't allow for symlinks under modules/
<!--- Verify first that your issue/request is not already reported in GitHub -->
##### ISSUE TYPE
- Bug Report
##### ANSIBLE VERSION

```
$ ansible --version
ansible 2.2.0 (devel 30e5999812) last updated 2016/05/09 10:56:55 (GMT -400)
  lib/ansible/modules/core: (devel 1f5cf669dd) last updated 2016/05/09 10:54:28 (GMT -400)
  lib/ansible/modules/extras: (devel bb965eebee) last updated 2016/05/09 10:43:13 (GMT -400)
  config file = 
  configured module search path = Default w/o overrides
```
##### CONFIGURATION

N/A
##### OS / ENVIRONMENT

CentOS 7
##### SUMMARY

Under lib/ansible/modules/, directories are traversed with os.walk. If the directories are not symlinks, they will be returned as possible module locations. If the directories are symlinks, os.walk ignores them and prevents usage of the modules found below.
##### STEPS TO REPRODUCE
1. Delete lib/ansible/modules/core
2. Symlink an ansible-modules-core checkout to lib/ansible/modules/core
3. ansible-doc -l and check for any core modules
4. None will be listed
##### EXPECTED RESULTS

All modules are listed in ansible-doc -l and are also available to ansible+ansible-playbook.
##### ACTUAL RESULTS

The modules are not found.



Discussion:

Resolving patch:
diff --git a/lib/ansible/plugins/__init__.py b/lib/ansible/plugins/__init__.py
--- a/lib/ansible/plugins/__init__.py
+++ b/lib/ansible/plugins/__init__.py
@@ -136,7 +136,7 @@ def print_paths(self):
     def _all_directories(self, dir):
         results = []
         results.append(dir)
-        for root, subdirs, files in os.walk(dir):
+        for root, subdirs, files in os.walk(dir, followlinks=True):
            if '__init__.py' in files:
                for x in subdirs:
                    results.append(os.path.join(root,x))


Test patch:
Repository: ansible/ansible

Issue:
Better FreeBSD distribution facts 
<!--- Verify first that your issue/request is not already reported in GitHub -->
##### ISSUE TYPE

<!--- Pick one below and delete the rest: -->
- Bug Report
##### ANSIBLE VERSION

```
ansible 2.2.0
  config file = /home/ale/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```
##### CONFIGURATION
##### OS / ENVIRONMENT

FreeBSD 10.2
##### SUMMARY

To write generic roles is fundamental to detect operating system version and release information.
The distribution_version does not show coherent version information on FreeBSD, additionally there's no distribution_major_version variable set.

<!--- Explain the problem briefly -->
##### STEPS TO REPRODUCE

$ ansible -i ./hosts -m setup local | grep distri
##### EXPECTED RESULTS

Having distribution_version coherent and ansible_distribution_major_version set makes possible to use this facts on generic tasks that works for linux and FreeBSD.

```
$ ansible -i ./hosts -m setup local | grep distri
        "ansible_distribution": "FreeBSD", 
        "ansible_distribution_major_version": "10", 
        "ansible_distribution_release": "10.2-RELEASE-p9", 
        "ansible_distribution_version": "10.2", 
```
##### ACTUAL RESULTS

The distribution_version is not quite usable, it should be a number as they are in the other platforms.

<!--- What actually happened? If possible run with high verbosity (-vvvv) -->

```
$ ansible -i ./hosts -m setup local | grep distri
        "ansible_distribution": "FreeBSD", 
        "ansible_distribution_release": "10.2-RELEASE-p9", 
        "ansible_distribution_version": "FreeBSD 10.2-RELEASE-p9 #0: Thu Jan 14 01:32:46 UTC 2016     root@amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC", 
```



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
@@ -675,7 +675,7 @@ def get_distribution_facts(self):
         self.facts['distribution_release'] = platform.release()
         self.facts['distribution_version'] = platform.version()
 
-        systems_implemented = ('AIX', 'HP-UX', 'Darwin', 'OpenBSD')
+        systems_implemented = ('AIX', 'HP-UX', 'Darwin', 'FreeBSD', 'OpenBSD')
 
         self.facts['distribution'] = self.system
 
@@ -764,6 +764,13 @@ def get_distribution_Darwin(self):
         data = out.split()[-1]
         self.facts['distribution_version'] = data
 
+    def get_distribution_FreeBSD(self):
+        self.facts['distribution_release'] = platform.release()
+        data = re.search('(\d+)\.(\d+)-RELEASE.*', self.facts['distribution_release'])
+        if data:
+            self.facts['distribution_major_version'] = data.group(1)
+            self.facts['distribution_version'] = '%s.%s' % (data.group(1), data.group(2))
+
     def get_distribution_OpenBSD(self):
         rc, out, err = self.module.run_command("/sbin/sysctl -n kern.version")
         match = re.match('OpenBSD\s[0-9]+.[0-9]+-(\S+)\s.*', out)


Test patch:
Repository: ansible/ansible

Issue:
contrib/vault/vault-keyring.py always fails with ansible 2.1
##### ISSUE TYPE
- Bug Report
##### ANSIBLE VERSION

```
ansible 2.2.0 (vault_explore 650bfdce8f) last updated 2016/05/24 17:12:58 (GMT -400)
  lib/ansible/modules/core: (detached HEAD a64d72d7bc) last updated 2016/05/23 10:31:41 (GMT -400)
  lib/ansible/modules/extras: (detached HEAD d2900e856b) last updated 2016/05/24 11:52:54 (GMT -400)
  config file = /Users/adrian/ansible/ansible.cfg
  configured module search path = ['/Users/adrian/ansible/my-modules', '/Users/adrian/ansible/lib/modules/core']

```
##### CONFIGURATION

ANSIBLE_CONFIG pointing to a ansible.cfg with:

```
[vault]
username = 'adrian'
```
##### OS / ENVIRONMENT

N/A
##### SUMMARY

contrib/vault/vault-keyring.py  always fails with:
`No [vault] section configured`

Regardless if the config does or does not have that section.

This appears to be because ansible.constants.load_config_file changed it's
return values to a tuple, causing an exception that is caught by the bare
except in vault-keyring.py which prints out the config error.

Got a patch to fix this ready headed to a pr.
##### STEPS TO REPRODUCE

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

add 

```
[vault]
username = 'doesntmattermuch'
```

to a ansible.cfg file that will be loaded by default.

run:

```
contrib/vault/vault-keyring.py
```
##### EXPECTED RESULTS

No error
##### ACTUAL RESULTS

```
No [vault] section configured
```



Discussion:

Resolving patch:
diff --git a/contrib/vault/vault-keyring.py b/contrib/vault/vault-keyring.py
old mode 100644
new mode 100755
--- a/contrib/vault/vault-keyring.py
+++ b/contrib/vault/vault-keyring.py
@@ -47,16 +47,17 @@
 import sys
 import getpass
 import keyring
+import ConfigParser
 
-import ansible.constants as C
 
+import ansible.constants as C
 
 def main():
-    parser = C.load_config_file()
+    (parser,config_path)  = C.load_config_file()
     try:
         username = parser.get('vault', 'username')
-    except:
-        sys.stderr.write('No [vault] section configured\n')
+    except ConfigParser.NoSectionError:
+        sys.stderr.write('No [vault] section configured in config file: %s\n' % config_path)
         sys.exit(1)
 
     if len(sys.argv) == 2 and sys.argv[1] == 'set':


Test patch:
Repository: ansible/ansible

Issue:
ec2.py has issues with large number of filters
##### ISSUE TYPE
- Bug Report
##### ANSIBLE VERSION

```
ansible 2.1.0.0
  config file = /Users/westover/.ansible.cfg
  configured module search path = ['/Users/westover/.ansible/modules/']
```
##### CONFIGURATION

Paths to hosts directory
##### OS / ENVIRONMENT

OS X 10.11
##### SUMMARY

ec2.py inventory script throwing errors blocks running of any playbook because default AWS credentials are associated with this account
##### STEPS TO REPRODUCE

```
~/.ansible/hosts/ec2.py --list
```
##### EXPECTED RESULTS

Returning of a list of AWS assets
##### ACTUAL RESULTS

The script exits and throws an error

```
~/.ansible/hosts/ec2.py --list
ERROR: "Error connecting to AWS backend.
The maximum number of filter values specified on a single call is 200", while: getting EC2 instances
```



Discussion:
Just ran into this exact same issue, started showing up once I got more than 200 instances in the region.


Resolving patch:
diff --git a/contrib/inventory/ec2.py b/contrib/inventory/ec2.py
--- a/contrib/inventory/ec2.py
+++ b/contrib/inventory/ec2.py
@@ -527,7 +527,12 @@ def get_instances_by_region(self, region):
             instance_ids = []
             for reservation in reservations:
                 instance_ids.extend([instance.id for instance in reservation.instances])
-            tags = conn.get_all_tags(filters={'resource-type': 'instance', 'resource-id': instance_ids})
+
+            max_filter_value = 199
+            tags = []
+            for i in range(0, len(instance_ids), max_filter_value):
+                tags.extend(conn.get_all_tags(filters={'resource-type': 'instance', 'resource-id': instance_ids[i:i+max_filter_value]}))
+
             tags_by_instance_id = defaultdict(dict)
             for tag in tags:
                 tags_by_instance_id[tag.res_id][tag.name] = tag.value


Test patch:
Repository: ansible/ansible

Issue:
synchronize module does not verify arguments properly
##### ISSUE TYPE
- Bug Report
##### ANSIBLE VERSION

ansible 2.1.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
##### OS / ENVIRONMENT

CentOS 7
##### SUMMARY

When creating a synchronize task with mode pull and wrongly named or missing src argument their is no  proper error message.
##### STEPS TO REPRODUCE

1) Create a playbook with a synchronize task with wrong arguments
2) Run this playbook

Example task:

```
- name: pull letsencrypt certificates
  synchronize:
    source: /etc/letsencrypt.sh/assembled
    mode: pull
    dest: /data/ansible/ssl_certs/assembled
```
##### EXPECTED RESULTS

A message indicating that src argument is missing (since it's wrongly named)
(or no message at all, because source could be an alias after all)
##### ACTUAL RESULTS

An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 124, in run
    res = self._execute()
  File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 446, in _execute
    result = self._handler.run(task_vars=variables)
  File "/usr/lib/python2.7/site-packages/ansible/plugins/action/synchronize.py", line 288, in run
    dest = self._process_origin(dest_host, dest, user)
  File "/usr/lib/python2.7/site-packages/ansible/plugins/action/synchronize.py", line 71, in _process_origin
    if ':' not in path and not path.startswith('/'):
TypeError: argument of type 'NoneType' is not iterable



Discussion:

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
@@ -266,6 +266,10 @@ def run(self, tmp=None, task_vars=None):
         # MUNGE SRC AND DEST PER REMOTE_HOST INFO
         src = self._task.args.get('src', None)
         dest = self._task.args.get('dest', None)
+        if src is None or dest is None:
+            return dict(failed=True,
+                    msg="synchronize requires both src and dest parameters are set")
+
         if not dest_is_local:
             # Private key handling
             if use_delegate:


Test patch:
Repository: ansible/ansible

Issue:
Unicode errors when running playbook with unicode under ansible 1.9.6
##### ISSUE TYPE
- Bug Report
##### ANSIBLE VERSION

```
[root@ip-10-65-202-196 _3120__ansible_playbooksgit_j]# ansible --version
ansible 1.9.6
  configured module search path = None
```
##### CONFIGURATION

All defaults.
##### OS / ENVIRONMENT

NA
##### SUMMARY

"UnicodeEncodeError" when running playbook with unicode.
##### STEPS TO REPRODUCE
- Create this [playbook](https://github.com/jlaska/ansible-playbooks/blob/master/utf-8-%E4%89%AA%E1%89%92%EC%B9%B8%E2%B1%B7%EA%AF%94%E5%99%82%ED%8F%84%E8%94%86%E3%AA%97%E8%BC%A5.yml), and call it `utf-8-䉪ቒ칸ⱷꯔ噂폄蔆㪗輥.yml`.
- Use the following inventory file:

```
[local]
127.0.0.1 ansible_connection=local ansible_python_interpreter='/usr/bin/env python'
```
##### EXPECTED RESULTS

Successful playbook run.
##### ACTUAL RESULTS

```
[root@ip-10-65-202-196 _3120__ansible_playbooksgit_j]# ansible-playbook -i inventory utf-8.yml 
Traceback (most recent call last):
  File "/usr/bin/ansible-playbook", line 324, in <module>
    sys.exit(main(sys.argv[1:]))
  File "/usr/bin/ansible-playbook", line 264, in main
    pb.run()
  File "/usr/lib/python2.6/site-packages/ansible/playbook/__init__.py", line 310, in run
    play = Play(self, play_ds, play_basedir, vault_password=self.vault_password)
  File "/usr/lib/python2.6/site-packages/ansible/playbook/play.py", line 194, in __init__
    self._tasks      = self._load_tasks(self._ds.get('tasks', []), load_vars)
  File "/usr/lib/python2.6/site-packages/ansible/playbook/play.py", line 606, in _load_tasks
    tokens = split_args(str(x['include']))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 65-74: ordinal not in range(128)
```



Discussion:

Resolving patch:
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
@@ -22,6 +22,7 @@
 from ansible import errors
 from ansible.playbook.task import Task
 from ansible.module_utils.splitter import split_args, unquote
+from ansible.utils.unicode import to_bytes
 import ansible.constants as C
 import pipes
 import shlex
@@ -603,7 +604,7 @@ def _load_tasks(self, tasks, vars=None, role_params=None, default_vars=None, bec
                     continue
 
             if 'include' in x:
-                tokens = split_args(str(x['include']))
+                tokens = split_args(to_bytes(x['include'], nonstring='simplerepr'))
                 included_additional_conditions = list(additional_conditions)
                 include_vars = {}
                 for k in x:


Test patch: