From 8a4d5856cef0a8a3a2673db62d7dfcafdb2b24db Mon Sep 17 00:00:00 2001
From: zimbatm <zimbatm@zimbatm.com>
Date: Mon, 27 Apr 2015 19:26:13 +0100
Subject: [PATCH 1/2] ec2_group: select own group if the name matches

This fixes an issue where multiple VPC have the same group name and
the one from the other VPC is selected.
---
 cloud/amazon/ec2_group.py | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/cloud/amazon/ec2_group.py b/cloud/amazon/ec2_group.py
index f84467740b3..eea69bc46c4 100644
--- a/cloud/amazon/ec2_group.py
+++ b/cloud/amazon/ec2_group.py
@@ -162,12 +162,12 @@ def get_target_from_rule(module, ec2, rule, name, group, groups, vpc_id):
         group_id = rule['group_id']
     elif 'group_name' in rule:
         group_name = rule['group_name']
-        if group_name in groups:
-            group_id = groups[group_name].id
-        elif group_name == name:
+        if group_name == name:
             group_id = group.id
             groups[group_id] = group
             groups[group_name] = group
+        elif group_name in groups:
+            group_id = groups[group_name].id
         else:
             if not rule.get('group_desc', '').strip():
                 module.fail_json(msg="group %s will be automatically created by rule %s and no description was provided" % (group_name, rule))

From 34378b6c6a6ca76098dd2e03a077524a4c645a59 Mon Sep 17 00:00:00 2001
From: zimbatm <zimbatm@zimbatm.com>
Date: Tue, 28 Apr 2015 10:19:20 +0100
Subject: [PATCH 2/2] ec2_group: prioritise current VPC group names over others

---
 cloud/amazon/ec2_group.py | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/cloud/amazon/ec2_group.py b/cloud/amazon/ec2_group.py
index eea69bc46c4..6552e5abf67 100644
--- a/cloud/amazon/ec2_group.py
+++ b/cloud/amazon/ec2_group.py
@@ -223,7 +223,12 @@ def main():
     groups = {}
     for curGroup in ec2.get_all_security_groups():
         groups[curGroup.id] = curGroup
-        groups[curGroup.name] = curGroup
+        if curGroup.name in groups:
+            # Prioritise groups from the current VPC
+            if vpc_id is None or curGroup.vpc_id == vpc_id:
+                groups[curGroup.name] = curGroup
+        else:
+            groups[curGroup.name] = curGroup
 
         if curGroup.name == name and (vpc_id is None or curGroup.vpc_id == vpc_id):
             group = curGroup