Repository: ansible/ansible

Issue:
Raise a warning when a reserved variable is set
As per [a list discussion](https://groups.google.com/forum/#!topic/ansible-project/fP0hX2Za4I0), it would be nice if a warning was printed if the user tries to set a reserved variable, such as `environment`.



Discussion:
Classifying this as a bug report so it doesn't get lost in the list.

+1, this had me stumped for a bit using "environment", and only figured it out after guessing it might be the case. 

Spent several hours figuring out why a variable named `environment` doesn't contain what I suppose it to contain.

+1 from me.

BTW, is there is a list of all things 'reserved'? Just not to stumble over such cases again...

not a central one, mostly we have some 'magic' internal vars and then keywords/directives for play, role and task.

I tried to pass a variable named port from a role definition like this:

```
- { role: myrole, port: '7689' }
```

The template module didn't like the port variable then like this:

```
AnsibleUndefinedVariable: ERROR! 'port' is undefined
```

The port variable was undefined till I renamed it to something else...

@meebey Yep. Very annoying, right? :)

I just bumped into this as well, exactly as @meeby did.

While I understand that the devs have more important things to do with currently more than 1k issues open, is there a list of reserved variables names somewhere, maybe a link to the code?

if only it where that simple, there are many and defined in different places

i added this for the basic objects, but far from a complete list http://docs.ansible.com/ansible/playbooks_directives.html 

thanks @bcoca!


Resolving patch:
diff --git a/lib/ansible/executor/task_queue_manager.py b/lib/ansible/executor/task_queue_manager.py
--- a/lib/ansible/executor/task_queue_manager.py
+++ b/lib/ansible/executor/task_queue_manager.py
@@ -36,6 +36,7 @@
 from ansible.template import Templar
 from ansible.utils.helpers import pct_to_int
 from ansible.vars.hostvars import HostVars
+from ansible.vars.reserved import warn_if_reserved
 
 try:
     from __main__ import display
@@ -209,6 +210,7 @@ def run(self, play):
             self.load_callbacks()
 
         all_vars = self._variable_manager.get_vars(loader=self._loader, play=play)
+        warn_if_reserved(all_vars)
         templar = Templar(loader=self._loader, variables=all_vars)
 
         new_play = play.copy()
diff --git a/lib/ansible/vars/__init__.py b/lib/ansible/vars/__init__.py
--- a/lib/ansible/vars/__init__.py
+++ b/lib/ansible/vars/__init__.py
@@ -92,6 +92,7 @@ def strip_internal_keys(dirty):
             clean[k] = strip_internal_keys(dirty[k])
     return clean
 
+
 class VariableManager:
 
     def __init__(self):
@@ -315,10 +316,10 @@ def get_vars(self, loader, play=None, host=None, task=None, include_hostvars=Tru
                                 for item in data:
                                     all_vars = combine_vars(all_vars, item)
                             break
-                        except AnsibleFileNotFound as e:
+                        except AnsibleFileNotFound:
                             # we continue on loader failures
                             continue
-                        except AnsibleParserError as e:
+                        except AnsibleParserError:
                             raise
                     else:
                         # if include_delegate_to is set to False, we ignore the missing
@@ -456,7 +457,7 @@ def _get_delegated_vars(self, loader, play, task, existing_variables):
                 try:
                     loop_terms = listify_lookup_plugin_terms(terms=task.loop_args, templar=templar, loader=loader, fail_on_undefined=True, convert_bare=False)
                     items = lookup_loader.get(task.loop, loader=loader, templar=templar).run(terms=loop_terms, variables=vars_copy)
-                except AnsibleUndefinedVariable as e:
+                except AnsibleUndefinedVariable:
                     # This task will be skipped later due to this, so we just setup
                     # a dummy array for the later code so it doesn't fail
                     items = [None]
diff --git a/lib/ansible/vars/reserved.py b/lib/ansible/vars/reserved.py
new file mode 100644
--- /dev/null
+++ b/lib/ansible/vars/reserved.py
@@ -0,0 +1,77 @@
+# (c) 2017 Ansible By Red Hat
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Ansible is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
+
+# Make coding more python3-ish
+from __future__ import (absolute_import, division, print_function)
+__metaclass__ = type
+
+from ansible.playbook import  Play
+from ansible.playbook.block import  Block
+from ansible.playbook.role import  Role
+from ansible.playbook.task import  Task
+
+try:
+    from __main__ import display
+except ImportError:
+    from ansible.utils.display import Display
+    display = Display()
+
+def get_reserved_names(include_private=True):
+    ''' this function returns the list of reserved names associated with play objects'''
+
+    public = set()
+    private = set()
+    result = set()
+
+    #FIXME: find a way to 'not hardcode', possibly need role deps/includes
+    class_list = [ Play, Role, Block, Task ]
+
+    for aclass in class_list:
+        aobj = aclass()
+
+        # build ordered list to loop over and dict with attributes
+        for attribute in aobj.__dict__['_attributes']:
+            if 'private' in attribute:
+                private.add(attribute)
+            else:
+                public.add(attribute)
+
+    # local_action is implicit with action
+    if 'action' in public:
+        public.add('local_action')
+
+    # loop implies with_
+    #FIXME: remove after with_ is not only deprecated but removed
+    if 'loop' in private or 'loop' in public:
+        public.add('with_')
+
+    if include_private:
+        result = public.union(private)
+    else:
+        result = public
+
+    return result
+
+def warn_if_reserved(myvars):
+    ''' this function warns if any variable passed conflicts with internally reserved names '''
+    reserved = get_reserved_names()
+    for varname in myvars:
+        if varname == 'vars':
+            continue # we add this one internally
+        if varname in reserved:
+            display.warning('Found variable using reserved name: %s' % varname)
+


Test patch: