Repository: ansible/ansible

Issue:
The inventory allows adding a group with an 'empty name' from dynamic inventory plugins
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### SUMMARY
<!--- Explain the problem briefly -->
When inventory plugin or script is used the inventory can created with empty named group which can leads to unexpected behavior:
https://github.com/ansible/ansible/issues/42040
https://github.com/ansible/ansible/issues/40228

The example project to demonstrate the issue:

https://github.com/ITD27M01/ansible-openstack-bug

The example of empty named group (from ansible-inventory --list):

https://github.com/ITD27M01/ansible-openstack-bug/blob/master/openstack-inventory.json#L2

##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
inventory
##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.5.5
  config file = /Users/igor.tiunov/Sources/ansible-openstack-bug/ansible.cfg
  configured module search path = [u'/Users/igor.tiunov/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python2.7/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 2.7.14 (default, Mar  9 2018, 23:57:12) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]
```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->
```
DEFAULT_HOST_LIST(/Users/igor.tiunov/Sources/ansible-openstack-bug/ansible.cfg) = [u'/Users/igor.tiunov/Sources/ansible-openstack-bug/openstack.yml']
DEFAULT_VAULT_PASSWORD_FILE(env: ANSIBLE_VAULT_PASSWORD_FILE) = /Users/igor.tiunov/tmp/.vault
INVENTORY_ENABLED(/Users/igor.tiunov/Sources/ansible-openstack-bug/ansible.cfg) = ['openstack']
```

##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->
Max OSX and rhel/windows instances on openstack
##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->

 1. Create clouds.yaml like this:
    https://github.com/ITD27M01/ansible-openstack-bug/blob/master/clouds.yaml
    https://docs.openstack.org/os-client-config/latest/user/configuration.html
2. Run ansible-invetnory --list
3. See the empty group in inventory:
    https://github.com/ITD27M01/ansible-openstack-bug/blob/master/openstack-inventory.json#L2
    https://github.com/ITD27M01/ansible-openstack-bug/blob/master/openstack-inventory.json#L260

<!--- Paste example playbooks or commands between quotes below -->
```yaml

```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
Empty named group is created
##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->
Empty named group is  not created
<!--- Paste verbatim command output between quotes below -->
```

```



Discussion:
Files identified in the description:
* [lib/ansible/inventory](https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
Im not sure this is a bug, since you can dynamically add hosts to a group afterwards
@bcoca 

The core problem not in ability to manage groups but in presents of empty named group. This is a poisonous group that can lead to non-obvious consequences.

Static inventory does not allow to create empty named group there is no any ability. And plugin should check the names of groups also - At least check an empty string.
individual plugins can have diff rules, i agree an empty name is an invalid group, but a group w/o hosts is not something i see as wrong by definition.
@bcoca 
Sorry for my English. This issue is not about empty groups or groups without hosts. This issue is about groups with names as empty string like this:

https://github.com/ITD27M01/ansible-openstack-bug/blob/master/openstack-inventory.json#L2


ok, that clearly is an error.
see if this patch fixes it for you
```diff --git a/lib/ansible/inventory/data.py b/lib/ansible/inventory/data.py
index dc730ff606..12c39f52ce 100644
--- a/lib/ansible/inventory/data.py
+++ b/lib/ansible/inventory/data.py
@@ -161,13 +161,16 @@ class InventoryData(object):
     def add_group(self, group):
         ''' adds a group to inventory if not there already '''

-        if group not in self.groups:
-            g = Group(group)
-            self.groups[group] = g
-            self._groups_dict_cache = {}
-            display.debug("Added group %s to inventory" % group)
+        if group:
+            if group not in self.groups:
+                g = Group(group)
+                self.groups[group] = g
+                self._groups_dict_cache = {}
+                display.debug("Added group %s to inventory" % group)
+            else:
+                display.debug("group %s already in inventory" % group)
         else:
-            display.debug("group %s already in inventory" % group)
+            display.warning("Ignoring empty/false group name: %s" % group)

     def remove_group(self, group):```

Resolving patch:
diff --git a/lib/ansible/inventory/data.py b/lib/ansible/inventory/data.py
--- a/lib/ansible/inventory/data.py
+++ b/lib/ansible/inventory/data.py
@@ -161,13 +161,16 @@ def get_host(self, hostname):
     def add_group(self, group):
         ''' adds a group to inventory if not there already '''
 
-        if group not in self.groups:
-            g = Group(group)
-            self.groups[group] = g
-            self._groups_dict_cache = {}
-            display.debug("Added group %s to inventory" % group)
+        if group:
+            if group not in self.groups:
+                g = Group(group)
+                self.groups[group] = g
+                self._groups_dict_cache = {}
+                display.debug("Added group %s to inventory" % group)
+            else:
+                display.debug("group %s already in inventory" % group)
         else:
-            display.debug("group %s already in inventory" % group)
+            raise AnsibleError("Invalid empty/false group name provided: %s" % group)
 
     def remove_group(self, group):
 
@@ -183,38 +186,41 @@ def remove_group(self, group):
     def add_host(self, host, group=None, port=None):
         ''' adds a host to inventory and possibly a group if not there already '''
 
-        g = None
-        if group:
-            if group in self.groups:
-                g = self.groups[group]
-            else:
-                raise AnsibleError("Could not find group %s in inventory" % group)
-
-        if host not in self.hosts:
-            h = Host(host, port)
-            self.hosts[host] = h
-            if self.current_source:  # set to 'first source' in which host was encountered
-                self.set_variable(host, 'inventory_file', self.current_source)
-                self.set_variable(host, 'inventory_dir', basedir(self.current_source))
-            else:
-                self.set_variable(host, 'inventory_file', None)
-                self.set_variable(host, 'inventory_dir', None)
-            display.debug("Added host %s to inventory" % (host))
-
-            # set default localhost from inventory to avoid creating an implicit one. Last localhost defined 'wins'.
-            if host in C.LOCALHOST:
-                if self.localhost is None:
-                    self.localhost = self.hosts[host]
-                    display.vvvv("Set default localhost to %s" % h)
+        if host:
+            g = None
+            if group:
+                if group in self.groups:
+                    g = self.groups[group]
                 else:
-                    display.warning("A duplicate localhost-like entry was found (%s). First found localhost was %s" % (h, self.localhost.name))
-        else:
-            h = self.hosts[host]
+                    raise AnsibleError("Could not find group %s in inventory" % group)
+
+            if host not in self.hosts:
+                h = Host(host, port)
+                self.hosts[host] = h
+                if self.current_source:  # set to 'first source' in which host was encountered
+                    self.set_variable(host, 'inventory_file', self.current_source)
+                    self.set_variable(host, 'inventory_dir', basedir(self.current_source))
+                else:
+                    self.set_variable(host, 'inventory_file', None)
+                    self.set_variable(host, 'inventory_dir', None)
+                display.debug("Added host %s to inventory" % (host))
+
+                # set default localhost from inventory to avoid creating an implicit one. Last localhost defined 'wins'.
+                if host in C.LOCALHOST:
+                    if self.localhost is None:
+                        self.localhost = self.hosts[host]
+                        display.vvvv("Set default localhost to %s" % h)
+                    else:
+                        display.warning("A duplicate localhost-like entry was found (%s). First found localhost was %s" % (h, self.localhost.name))
+            else:
+                h = self.hosts[host]
 
-        if g:
-            g.add_host(h)
-            self._groups_dict_cache = {}
-            display.debug("Added host %s to group %s" % (host, group))
+            if g:
+                g.add_host(h)
+                self._groups_dict_cache = {}
+                display.debug("Added host %s to group %s" % (host, group))
+        else:
+            raise AnsibleError("Invalid empty host name provided: %s" % host)
 
     def remove_host(self, host):
 


Test patch: