Merge pull request #1162 from hashicorp/aws-go-security-groups

provider/aws: Convert AWS Security Groups to aws-sdk-go
This commit is contained in:
Clint 2015-03-11 08:33:01 -05:00
commit 344382df2e
4 changed files with 212 additions and 254 deletions

View File

@ -7,10 +7,11 @@ import (
"sort" "sort"
"time" "time"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/ec2"
"github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/schema"
"github.com/mitchellh/goamz/ec2"
) )
func resourceAwsSecurityGroup() *schema.Resource { func resourceAwsSecurityGroup() *schema.Resource {
@ -141,18 +142,18 @@ func resourceAwsSecurityGroup() *schema.Resource {
} }
func resourceAwsSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { func resourceAwsSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn ec2conn := meta.(*AWSClient).awsEC2conn
securityGroupOpts := ec2.SecurityGroup{ securityGroupOpts := &ec2.CreateSecurityGroupRequest{
Name: d.Get("name").(string), GroupName: aws.String(d.Get("name").(string)),
} }
if v := d.Get("vpc_id"); v != nil { if v := d.Get("vpc_id"); v != nil {
securityGroupOpts.VpcId = v.(string) securityGroupOpts.VPCID = aws.String(v.(string))
} }
if v := d.Get("description"); v != nil { if v := d.Get("description"); v != nil {
securityGroupOpts.Description = v.(string) securityGroupOpts.Description = aws.String(v.(string))
} }
log.Printf( log.Printf(
@ -162,7 +163,7 @@ func resourceAwsSecurityGroupCreate(d *schema.ResourceData, meta interface{}) er
return fmt.Errorf("Error creating Security Group: %s", err) return fmt.Errorf("Error creating Security Group: %s", err)
} }
d.SetId(createResp.Id) d.SetId(*createResp.GroupID)
log.Printf("[INFO] Security Group ID: %s", d.Id()) log.Printf("[INFO] Security Group ID: %s", d.Id())
@ -186,7 +187,7 @@ func resourceAwsSecurityGroupCreate(d *schema.ResourceData, meta interface{}) er
} }
func resourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { func resourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn ec2conn := meta.(*AWSClient).awsEC2conn
sgRaw, _, err := SGStateRefreshFunc(ec2conn, d.Id())() sgRaw, _, err := SGStateRefreshFunc(ec2conn, d.Id())()
if err != nil { if err != nil {
@ -197,24 +198,23 @@ func resourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) erro
return nil return nil
} }
sg := sgRaw.(*ec2.SecurityGroupInfo) sg := sgRaw.(ec2.SecurityGroup)
ingressRules := resourceAwsSecurityGroupIPPermGather(d, sg.IPPerms) ingressRules := resourceAwsSecurityGroupIPPermGather(d, sg.IPPermissions)
egressRules := resourceAwsSecurityGroupIPPermGather(d, sg.IPPermsEgress) egressRules := resourceAwsSecurityGroupIPPermGather(d, sg.IPPermissionsEgress)
d.Set("description", sg.Description) d.Set("description", sg.Description)
d.Set("name", sg.Name) d.Set("name", sg.GroupName)
d.Set("vpc_id", sg.VpcId) d.Set("vpc_id", sg.VPCID)
d.Set("owner_id", sg.OwnerId) d.Set("owner_id", sg.OwnerID)
d.Set("ingress", ingressRules) d.Set("ingress", ingressRules)
d.Set("egress", egressRules) d.Set("egress", egressRules)
d.Set("tags", tagsToMap(sg.Tags)) d.Set("tags", tagsToMapSDK(sg.Tags))
return nil return nil
} }
func resourceAwsSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error { func resourceAwsSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn ec2conn := meta.(*AWSClient).awsEC2conn
sgRaw, _, err := SGStateRefreshFunc(ec2conn, d.Id())() sgRaw, _, err := SGStateRefreshFunc(ec2conn, d.Id())()
if err != nil { if err != nil {
@ -224,7 +224,8 @@ func resourceAwsSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) er
d.SetId("") d.SetId("")
return nil return nil
} }
group := sgRaw.(*ec2.SecurityGroupInfo).SecurityGroup
group := sgRaw.(ec2.SecurityGroup)
err = resourceAwsSecurityGroupUpdateRules(d, "ingress", meta, group) err = resourceAwsSecurityGroupUpdateRules(d, "ingress", meta, group)
if err != nil { if err != nil {
@ -238,7 +239,7 @@ func resourceAwsSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) er
} }
} }
if err := setTags(ec2conn, d); err != nil { if err := setTagsSDK(ec2conn, d); err != nil {
return err return err
} }
@ -248,14 +249,16 @@ func resourceAwsSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) er
} }
func resourceAwsSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { func resourceAwsSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn ec2conn := meta.(*AWSClient).awsEC2conn
log.Printf("[DEBUG] Security Group destroy: %v", d.Id()) log.Printf("[DEBUG] Security Group destroy: %v", d.Id())
return resource.Retry(5*time.Minute, func() error { return resource.Retry(5*time.Minute, func() error {
_, err := ec2conn.DeleteSecurityGroup(ec2.SecurityGroup{Id: d.Id()}) err := ec2conn.DeleteSecurityGroup(&ec2.DeleteSecurityGroupRequest{
GroupID: aws.String(d.Id()),
})
if err != nil { if err != nil {
ec2err, ok := err.(*ec2.Error) ec2err, ok := err.(aws.APIError)
if !ok { if !ok {
return err return err
} }
@ -313,34 +316,45 @@ func resourceAwsSecurityGroupRuleHash(v interface{}) int {
return hashcode.String(buf.String()) return hashcode.String(buf.String())
} }
func resourceAwsSecurityGroupIPPermGather(d *schema.ResourceData, permissions []ec2.IPPerm) []map[string]interface{} { func resourceAwsSecurityGroupIPPermGather(d *schema.ResourceData, permissions []ec2.IPPermission) []map[string]interface{} {
ruleMap := make(map[string]map[string]interface{}) ruleMap := make(map[string]map[string]interface{})
for _, perm := range permissions { for _, perm := range permissions {
k := fmt.Sprintf("%s-%d-%d", perm.Protocol, perm.FromPort, perm.ToPort) var fromPort, toPort int
if v := perm.FromPort; v != nil {
fromPort = *v
}
if v := perm.ToPort; v != nil {
toPort = *v
}
k := fmt.Sprintf("%s-%d-%d", *perm.IPProtocol, fromPort, toPort)
m, ok := ruleMap[k] m, ok := ruleMap[k]
if !ok { if !ok {
m = make(map[string]interface{}) m = make(map[string]interface{})
ruleMap[k] = m ruleMap[k] = m
} }
m["from_port"] = perm.FromPort m["from_port"] = fromPort
m["to_port"] = perm.ToPort m["to_port"] = toPort
m["protocol"] = perm.Protocol m["protocol"] = *perm.IPProtocol
if len(perm.SourceIPs) > 0 { if len(perm.IPRanges) > 0 {
raw, ok := m["cidr_blocks"] raw, ok := m["cidr_blocks"]
if !ok { if !ok {
raw = make([]string, 0, len(perm.SourceIPs)) raw = make([]string, 0, len(perm.IPRanges))
} }
list := raw.([]string) list := raw.([]string)
list = append(list, perm.SourceIPs...) for _, ip := range perm.IPRanges {
list = append(list, *ip.CIDRIP)
}
m["cidr_blocks"] = list m["cidr_blocks"] = list
} }
var groups []string var groups []string
if len(perm.SourceGroups) > 0 { if len(perm.UserIDGroupPairs) > 0 {
groups = flattenSecurityGroups(perm.SourceGroups) groups = flattenSecurityGroupsSDK(perm.UserIDGroupPairs)
} }
for i, id := range groups { for i, id := range groups {
if id == d.Id() { if id == d.Id() {
@ -364,7 +378,6 @@ func resourceAwsSecurityGroupIPPermGather(d *schema.ResourceData, permissions []
for _, m := range ruleMap { for _, m := range ruleMap {
rules = append(rules, m) rules = append(rules, m)
} }
return rules return rules
} }
@ -383,6 +396,7 @@ func resourceAwsSecurityGroupUpdateRules(
os := o.(*schema.Set) os := o.(*schema.Set)
ns := n.(*schema.Set) ns := n.(*schema.Set)
// TODO: re-munge this when test is updated
remove := expandIPPerms(d.Id(), os.Difference(ns).List()) remove := expandIPPerms(d.Id(), os.Difference(ns).List())
add := expandIPPerms(d.Id(), ns.Difference(os).List()) add := expandIPPerms(d.Id(), ns.Difference(os).List())
@ -396,34 +410,53 @@ func resourceAwsSecurityGroupUpdateRules(
// not have service issues. // not have service issues.
if len(remove) > 0 || len(add) > 0 { if len(remove) > 0 || len(add) > 0 {
ec2conn := meta.(*AWSClient).ec2conn ec2conn := meta.(*AWSClient).awsEC2conn
var err error
if len(remove) > 0 { if len(remove) > 0 {
// Revoke the old rules log.Printf("[DEBUG] Revoking security group %#v %s rule: %#v",
revoke := ec2conn.RevokeSecurityGroup group, ruleset, remove)
if ruleset == "egress" { if ruleset == "egress" {
revoke = ec2conn.RevokeSecurityGroupEgress req := &ec2.RevokeSecurityGroupEgressRequest{
GroupID: group.GroupID,
IPPermissions: remove,
}
err = ec2conn.RevokeSecurityGroupEgress(req)
} else {
req := &ec2.RevokeSecurityGroupIngressRequest{
GroupID: group.GroupID,
IPPermissions: remove,
}
err = ec2conn.RevokeSecurityGroupIngress(req)
} }
log.Printf("[DEBUG] Revoking security group %s %s rule: %#v", if err != nil {
group, ruleset, remove)
if _, err := revoke(group, remove); err != nil {
return fmt.Errorf( return fmt.Errorf(
"Error revoking security group %s rules: %s", "Error authorizing security group %s rules: %s",
ruleset, err) ruleset, err)
} }
} }
if len(add) > 0 { if len(add) > 0 {
log.Printf("[DEBUG] Authorizing security group %#v %s rule: %#v",
group, ruleset, add)
// Authorize the new rules // Authorize the new rules
authorize := ec2conn.AuthorizeSecurityGroup
if ruleset == "egress" { if ruleset == "egress" {
authorize = ec2conn.AuthorizeSecurityGroupEgress req := &ec2.AuthorizeSecurityGroupEgressRequest{
GroupID: group.GroupID,
IPPermissions: add,
}
err = ec2conn.AuthorizeSecurityGroupEgress(req)
} else {
req := &ec2.AuthorizeSecurityGroupIngressRequest{
GroupID: group.GroupID,
IPPermissions: add,
}
err = ec2conn.AuthorizeSecurityGroupIngress(req)
} }
log.Printf("[DEBUG] Authorizing security group %s %s rule: %#v", if err != nil {
group, ruleset, add)
if _, err := authorize(group, add); err != nil {
return fmt.Errorf( return fmt.Errorf(
"Error authorizing security group %s rules: %s", "Error authorizing security group %s rules: %s",
ruleset, err) ruleset, err)
@ -431,7 +464,6 @@ func resourceAwsSecurityGroupUpdateRules(
} }
} }
} }
return nil return nil
} }
@ -439,10 +471,12 @@ func resourceAwsSecurityGroupUpdateRules(
// a security group. // a security group.
func SGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc { func SGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { return func() (interface{}, string, error) {
sgs := []ec2.SecurityGroup{ec2.SecurityGroup{Id: id}} req := &ec2.DescribeSecurityGroupsRequest{
resp, err := conn.SecurityGroups(sgs, nil) GroupIDs: []string{id},
}
resp, err := conn.DescribeSecurityGroups(req)
if err != nil { if err != nil {
if ec2err, ok := err.(*ec2.Error); ok { if ec2err, ok := err.(aws.APIError); ok {
if ec2err.Code == "InvalidSecurityGroupID.NotFound" || if ec2err.Code == "InvalidSecurityGroupID.NotFound" ||
ec2err.Code == "InvalidGroup.NotFound" { ec2err.Code == "InvalidGroup.NotFound" {
resp = nil resp = nil
@ -460,7 +494,7 @@ func SGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
return nil, "", nil return nil, "", nil
} }
group := &resp.Groups[0] group := resp.SecurityGroups[0]
return group, "exists", nil return group, "exists", nil
} }
} }

View File

@ -2,16 +2,18 @@ package aws
import ( import (
"fmt" "fmt"
"log"
"reflect" "reflect"
"testing" "testing"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/ec2"
"github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/goamz/ec2"
) )
func TestAccAWSSecurityGroup_normal(t *testing.T) { func TestAccAWSSecurityGroup_normal(t *testing.T) {
var group ec2.SecurityGroupInfo var group ec2.SecurityGroup
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
@ -44,7 +46,7 @@ func TestAccAWSSecurityGroup_normal(t *testing.T) {
} }
func TestAccAWSSecurityGroup_self(t *testing.T) { func TestAccAWSSecurityGroup_self(t *testing.T) {
var group ec2.SecurityGroupInfo var group ec2.SecurityGroup
checkSelf := func(s *terraform.State) (err error) { checkSelf := func(s *terraform.State) (err error) {
defer func() { defer func() {
@ -53,7 +55,7 @@ func TestAccAWSSecurityGroup_self(t *testing.T) {
} }
}() }()
if group.IPPerms[0].SourceGroups[0].Id != group.Id { if *group.IPPermissions[0].UserIDGroupPairs[0].GroupID != *group.GroupID {
return fmt.Errorf("bad: %#v", group) return fmt.Errorf("bad: %#v", group)
} }
@ -89,10 +91,10 @@ func TestAccAWSSecurityGroup_self(t *testing.T) {
} }
func TestAccAWSSecurityGroup_vpc(t *testing.T) { func TestAccAWSSecurityGroup_vpc(t *testing.T) {
var group ec2.SecurityGroupInfo var group ec2.SecurityGroup
testCheck := func(*terraform.State) error { testCheck := func(*terraform.State) error {
if group.VpcId == "" { if *group.VPCID == "" {
return fmt.Errorf("should have vpc ID") return fmt.Errorf("should have vpc ID")
} }
@ -141,7 +143,7 @@ func TestAccAWSSecurityGroup_vpc(t *testing.T) {
} }
func TestAccAWSSecurityGroup_MultiIngress(t *testing.T) { func TestAccAWSSecurityGroup_MultiIngress(t *testing.T) {
var group ec2.SecurityGroupInfo var group ec2.SecurityGroup
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
@ -159,7 +161,7 @@ func TestAccAWSSecurityGroup_MultiIngress(t *testing.T) {
} }
func TestAccAWSSecurityGroup_Change(t *testing.T) { func TestAccAWSSecurityGroup_Change(t *testing.T) {
var group ec2.SecurityGroupInfo var group ec2.SecurityGroup
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
@ -184,30 +186,27 @@ func TestAccAWSSecurityGroup_Change(t *testing.T) {
} }
func testAccCheckAWSSecurityGroupDestroy(s *terraform.State) error { func testAccCheckAWSSecurityGroupDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).ec2conn conn := testAccProvider.Meta().(*AWSClient).awsEC2conn
for _, rs := range s.RootModule().Resources { for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_security_group" { if rs.Type != "aws_security_group" {
continue continue
} }
sgs := []ec2.SecurityGroup{
ec2.SecurityGroup{
Id: rs.Primary.ID,
},
}
// Retrieve our group // Retrieve our group
resp, err := conn.SecurityGroups(sgs, nil) req := &ec2.DescribeSecurityGroupsRequest{
GroupIDs: []string{rs.Primary.ID},
}
resp, err := conn.DescribeSecurityGroups(req)
if err == nil { if err == nil {
if len(resp.Groups) > 0 && resp.Groups[0].Id == rs.Primary.ID { if len(resp.SecurityGroups) > 0 && *resp.SecurityGroups[0].GroupID == rs.Primary.ID {
return fmt.Errorf("Security Group (%s) still exists.", rs.Primary.ID) return fmt.Errorf("Security Group (%s) still exists.", rs.Primary.ID)
} }
return nil return nil
} }
ec2err, ok := err.(*ec2.Error) ec2err, ok := err.(aws.APIError)
if !ok { if !ok {
return err return err
} }
@ -220,7 +219,7 @@ func testAccCheckAWSSecurityGroupDestroy(s *terraform.State) error {
return nil return nil
} }
func testAccCheckAWSSecurityGroupExists(n string, group *ec2.SecurityGroupInfo) resource.TestCheckFunc { func testAccCheckAWSSecurityGroupExists(n string, group *ec2.SecurityGroup) resource.TestCheckFunc {
return func(s *terraform.State) error { return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n] rs, ok := s.RootModule().Resources[n]
if !ok { if !ok {
@ -231,20 +230,19 @@ func testAccCheckAWSSecurityGroupExists(n string, group *ec2.SecurityGroupInfo)
return fmt.Errorf("No Security Group is set") return fmt.Errorf("No Security Group is set")
} }
conn := testAccProvider.Meta().(*AWSClient).ec2conn conn := testAccProvider.Meta().(*AWSClient).awsEC2conn
sgs := []ec2.SecurityGroup{ req := &ec2.DescribeSecurityGroupsRequest{
ec2.SecurityGroup{ GroupIDs: []string{rs.Primary.ID},
Id: rs.Primary.ID,
},
} }
resp, err := conn.SecurityGroups(sgs, nil) resp, err := conn.DescribeSecurityGroups(req)
if err != nil { if err != nil {
return err return err
} }
if len(resp.Groups) > 0 && resp.Groups[0].Id == rs.Primary.ID { if len(resp.SecurityGroups) > 0 && *resp.SecurityGroups[0].GroupID == rs.Primary.ID {
*group = resp.Groups[0] log.Printf("\n==\n===\nfound group\n===\n==\n")
*group = resp.SecurityGroups[0]
return nil return nil
} }
@ -253,32 +251,32 @@ func testAccCheckAWSSecurityGroupExists(n string, group *ec2.SecurityGroupInfo)
} }
} }
func testAccCheckAWSSecurityGroupAttributes(group *ec2.SecurityGroupInfo) resource.TestCheckFunc { func testAccCheckAWSSecurityGroupAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc {
return func(s *terraform.State) error { return func(s *terraform.State) error {
p := ec2.IPPerm{ p := ec2.IPPermission{
FromPort: 80, FromPort: aws.Integer(80),
ToPort: 8000, ToPort: aws.Integer(8000),
Protocol: "tcp", IPProtocol: aws.String("tcp"),
SourceIPs: []string{"10.0.0.0/8"}, IPRanges: []ec2.IPRange{ec2.IPRange{aws.String("10.0.0.0/8")}},
} }
if group.Name != "terraform_acceptance_test_example" { if *group.GroupName != "terraform_acceptance_test_example" {
return fmt.Errorf("Bad name: %s", group.Name) return fmt.Errorf("Bad name: %s", *group.GroupName)
} }
if group.Description != "Used in the terraform acceptance tests" { if *group.Description != "Used in the terraform acceptance tests" {
return fmt.Errorf("Bad description: %s", group.Description) return fmt.Errorf("Bad description: %s", *group.Description)
} }
if len(group.IPPerms) == 0 { if len(group.IPPermissions) == 0 {
return fmt.Errorf("No IPPerms") return fmt.Errorf("No IPPerms")
} }
// Compare our ingress // Compare our ingress
if !reflect.DeepEqual(group.IPPerms[0], p) { if !reflect.DeepEqual(group.IPPermissions[0], p) {
return fmt.Errorf( return fmt.Errorf(
"Got:\n\n%#v\n\nExpected:\n\n%#v\n", "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
group.IPPerms[0], group.IPPermissions[0],
p) p)
} }
@ -287,7 +285,7 @@ func testAccCheckAWSSecurityGroupAttributes(group *ec2.SecurityGroupInfo) resour
} }
func TestAccAWSSecurityGroup_tags(t *testing.T) { func TestAccAWSSecurityGroup_tags(t *testing.T) {
var group ec2.SecurityGroupInfo var group ec2.SecurityGroup
resource.Test(t, resource.TestCase{ resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
@ -298,7 +296,7 @@ func TestAccAWSSecurityGroup_tags(t *testing.T) {
Config: testAccAWSSecurityGroupConfigTags, Config: testAccAWSSecurityGroupConfigTags,
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSecurityGroupExists("aws_security_group.foo", &group), testAccCheckAWSSecurityGroupExists("aws_security_group.foo", &group),
testAccCheckTags(&group.Tags, "foo", "bar"), testAccCheckTagsSDK(&group.Tags, "foo", "bar"),
), ),
}, },
@ -306,56 +304,56 @@ func TestAccAWSSecurityGroup_tags(t *testing.T) {
Config: testAccAWSSecurityGroupConfigTagsUpdate, Config: testAccAWSSecurityGroupConfigTagsUpdate,
Check: resource.ComposeTestCheckFunc( Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSecurityGroupExists("aws_security_group.foo", &group), testAccCheckAWSSecurityGroupExists("aws_security_group.foo", &group),
testAccCheckTags(&group.Tags, "foo", ""), testAccCheckTagsSDK(&group.Tags, "foo", ""),
testAccCheckTags(&group.Tags, "bar", "baz"), testAccCheckTagsSDK(&group.Tags, "bar", "baz"),
), ),
}, },
}, },
}) })
} }
func testAccCheckAWSSecurityGroupAttributesChanged(group *ec2.SecurityGroupInfo) resource.TestCheckFunc { func testAccCheckAWSSecurityGroupAttributesChanged(group *ec2.SecurityGroup) resource.TestCheckFunc {
return func(s *terraform.State) error { return func(s *terraform.State) error {
p := []ec2.IPPerm{ p := []ec2.IPPermission{
ec2.IPPerm{ ec2.IPPermission{
FromPort: 80, FromPort: aws.Integer(80),
ToPort: 9000, ToPort: aws.Integer(9000),
Protocol: "tcp", IPProtocol: aws.String("tcp"),
SourceIPs: []string{"10.0.0.0/8"}, IPRanges: []ec2.IPRange{ec2.IPRange{aws.String("10.0.0.0/8")}},
}, },
ec2.IPPerm{ ec2.IPPermission{
FromPort: 80, FromPort: aws.Integer(80),
ToPort: 8000, ToPort: aws.Integer(8000),
Protocol: "tcp", IPProtocol: aws.String("tcp"),
SourceIPs: []string{"0.0.0.0/0", "10.0.0.0/8"}, IPRanges: []ec2.IPRange{ec2.IPRange{aws.String("0.0.0.0/0")}, ec2.IPRange{aws.String("10.0.0.0/8")}},
}, },
} }
if group.Name != "terraform_acceptance_test_example" { if *group.GroupName != "terraform_acceptance_test_example" {
return fmt.Errorf("Bad name: %s", group.Name) return fmt.Errorf("Bad name: %s", *group.GroupName)
} }
if group.Description != "Used in the terraform acceptance tests" { if *group.Description != "Used in the terraform acceptance tests" {
return fmt.Errorf("Bad description: %s", group.Description) return fmt.Errorf("Bad description: %s", *group.Description)
} }
// Compare our ingress // Compare our ingress
if len(group.IPPerms) != 2 { if len(group.IPPermissions) != 2 {
return fmt.Errorf( return fmt.Errorf(
"Got:\n\n%#v\n\nExpected:\n\n%#v\n", "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
group.IPPerms, group.IPPermissions,
p) p)
} }
if group.IPPerms[0].ToPort == 8000 { if *group.IPPermissions[0].ToPort == 8000 {
group.IPPerms[1], group.IPPerms[0] = group.IPPermissions[1], group.IPPermissions[0] =
group.IPPerms[0], group.IPPerms[1] group.IPPermissions[0], group.IPPermissions[1]
} }
if !reflect.DeepEqual(group.IPPerms, p) { if !reflect.DeepEqual(group.IPPermissions, p) {
return fmt.Errorf( return fmt.Errorf(
"Got:\n\n%#v\n\nExpected:\n\n%#v\n", "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
group.IPPerms, group.IPPermissions,
p) p)
} }

View File

@ -4,6 +4,7 @@ import (
"strings" "strings"
"github.com/hashicorp/aws-sdk-go/aws" "github.com/hashicorp/aws-sdk-go/aws"
awsEC2 "github.com/hashicorp/aws-sdk-go/gen/ec2"
"github.com/hashicorp/aws-sdk-go/gen/elb" "github.com/hashicorp/aws-sdk-go/gen/elb"
"github.com/hashicorp/aws-sdk-go/gen/rds" "github.com/hashicorp/aws-sdk-go/gen/rds"
"github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/schema"
@ -39,15 +40,15 @@ func expandListeners(configured []interface{}) ([]elb.Listener, error) {
// Takes the result of flatmap.Expand for an array of ingress/egress // Takes the result of flatmap.Expand for an array of ingress/egress
// security group rules and returns EC2 API compatible objects // security group rules and returns EC2 API compatible objects
func expandIPPerms(id string, configured []interface{}) []ec2.IPPerm { func expandIPPerms(id string, configured []interface{}) []awsEC2.IPPermission {
perms := make([]ec2.IPPerm, len(configured)) perms := make([]awsEC2.IPPermission, len(configured))
for i, mRaw := range configured { for i, mRaw := range configured {
var perm ec2.IPPerm var perm awsEC2.IPPermission
m := mRaw.(map[string]interface{}) m := mRaw.(map[string]interface{})
perm.FromPort = m["from_port"].(int) perm.FromPort = aws.Integer(m["from_port"].(int))
perm.ToPort = m["to_port"].(int) perm.ToPort = aws.Integer(m["to_port"].(int))
perm.Protocol = m["protocol"].(string) perm.IPProtocol = aws.String(m["protocol"].(string))
var groups []string var groups []string
if raw, ok := m["security_groups"]; ok { if raw, ok := m["security_groups"]; ok {
@ -61,25 +62,25 @@ func expandIPPerms(id string, configured []interface{}) []ec2.IPPerm {
} }
if len(groups) > 0 { if len(groups) > 0 {
perm.SourceGroups = make([]ec2.UserSecurityGroup, len(groups)) perm.UserIDGroupPairs = make([]awsEC2.UserIDGroupPair, len(groups))
for i, name := range groups { for i, name := range groups {
ownerId, id := "", name ownerId, id := "", name
if items := strings.Split(id, "/"); len(items) > 1 { if items := strings.Split(id, "/"); len(items) > 1 {
ownerId, id = items[0], items[1] ownerId, id = items[0], items[1]
} }
perm.SourceGroups[i] = ec2.UserSecurityGroup{ perm.UserIDGroupPairs[i] = awsEC2.UserIDGroupPair{
Id: id, GroupID: aws.String(id),
OwnerId: ownerId, UserID: aws.String(ownerId),
} }
} }
} }
if raw, ok := m["cidr_blocks"]; ok { if raw, ok := m["cidr_blocks"]; ok {
list := raw.([]interface{}) list := raw.([]interface{})
perm.SourceIPs = make([]string, len(list)) perm.IPRanges = make([]awsEC2.IPRange, len(list))
for i, v := range list { for i, v := range list {
perm.SourceIPs[i] = v.(string) perm.IPRanges[i] = awsEC2.IPRange{aws.String(v.(string))}
} }
} }
@ -111,31 +112,6 @@ func expandParameters(configured []interface{}) ([]rds.Parameter, error) {
return parameters, nil return parameters, nil
} }
// Flattens an array of ipPerms into a list of primitives that
// flatmap.Flatten() can handle
func flattenIPPerms(list []ec2.IPPerm) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, perm := range list {
n := make(map[string]interface{})
n["from_port"] = perm.FromPort
n["protocol"] = perm.Protocol
n["to_port"] = perm.ToPort
if len(perm.SourceIPs) > 0 {
n["cidr_blocks"] = perm.SourceIPs
}
if v := flattenSecurityGroups(perm.SourceGroups); len(v) > 0 {
n["security_groups"] = v
}
result = append(result, n)
}
return result
}
// Flattens a health check into something that flatmap.Flatten() // Flattens a health check into something that flatmap.Flatten()
// can handle // can handle
func flattenHealthCheck(check *elb.HealthCheck) []map[string]interface{} { func flattenHealthCheck(check *elb.HealthCheck) []map[string]interface{} {
@ -162,6 +138,15 @@ func flattenSecurityGroups(list []ec2.UserSecurityGroup) []string {
return result return result
} }
// Flattens an array of UserSecurityGroups into a []string
func flattenSecurityGroupsSDK(list []awsEC2.UserIDGroupPair) []string {
result := make([]string, 0, len(list))
for _, g := range list {
result = append(result, *g.GroupID)
}
return result
}
// Flattens an array of Instances into a []string // Flattens an array of Instances into a []string
func flattenInstances(list []elb.Instance) []string { func flattenInstances(list []elb.Instance) []string {
result := make([]string, 0, len(list)) result := make([]string, 0, len(list))

View File

@ -1,16 +1,17 @@
package aws package aws
import ( import (
"log"
"reflect" "reflect"
"testing" "testing"
"github.com/hashicorp/aws-sdk-go/aws" "github.com/hashicorp/aws-sdk-go/aws"
awsEC2 "github.com/hashicorp/aws-sdk-go/gen/ec2"
"github.com/hashicorp/aws-sdk-go/gen/elb" "github.com/hashicorp/aws-sdk-go/gen/elb"
"github.com/hashicorp/aws-sdk-go/gen/rds" "github.com/hashicorp/aws-sdk-go/gen/rds"
"github.com/hashicorp/terraform/flatmap" "github.com/hashicorp/terraform/flatmap"
"github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/schema"
"github.com/mitchellh/goamz/ec2"
) )
// Returns test configuration // Returns test configuration
@ -61,120 +62,60 @@ func TestExpandIPPerms(t *testing.T) {
} }
perms := expandIPPerms("foo", expanded) perms := expandIPPerms("foo", expanded)
expected := []ec2.IPPerm{ log.Printf("wtf is perms:\n%#v", perms)
ec2.IPPerm{
Protocol: "icmp", expected := []awsEC2.IPPermission{
FromPort: 1, awsEC2.IPPermission{
ToPort: -1, IPProtocol: aws.String("icmp"),
SourceIPs: []string{"0.0.0.0/0"}, FromPort: aws.Integer(1),
SourceGroups: []ec2.UserSecurityGroup{ ToPort: aws.Integer(-1),
ec2.UserSecurityGroup{ IPRanges: []awsEC2.IPRange{awsEC2.IPRange{aws.String("0.0.0.0/0")}},
OwnerId: "foo", UserIDGroupPairs: []awsEC2.UserIDGroupPair{
Id: "sg-22222", awsEC2.UserIDGroupPair{
UserID: aws.String("foo"),
GroupID: aws.String("sg-22222"),
}, },
ec2.UserSecurityGroup{ awsEC2.UserIDGroupPair{
Id: "sg-11111", GroupID: aws.String("sg-22222"),
}, },
}, },
}, },
ec2.IPPerm{ awsEC2.IPPermission{
Protocol: "icmp", IPProtocol: aws.String("icmp"),
FromPort: 1, FromPort: aws.Integer(1),
ToPort: -1, ToPort: aws.Integer(-1),
SourceGroups: []ec2.UserSecurityGroup{ UserIDGroupPairs: []awsEC2.UserIDGroupPair{
ec2.UserSecurityGroup{ awsEC2.UserIDGroupPair{
Id: "foo", UserID: aws.String("foo"),
}, },
}, },
}, },
} }
if !reflect.DeepEqual(perms, expected) { exp := expected[0]
perm := perms[0]
if *exp.FromPort != *perm.FromPort {
t.Fatalf( t.Fatalf(
"Got:\n\n%#v\n\nExpected:\n\n%#v\n", "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
perms[0], *perm.FromPort,
expected) *exp.FromPort)
} }
} if *exp.IPRanges[0].CIDRIP != *perm.IPRanges[0].CIDRIP {
t.Fatalf(
func TestFlattenIPPerms(t *testing.T) { "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
cases := []struct { *perm.IPRanges[0].CIDRIP,
Input []ec2.IPPerm *exp.IPRanges[0].CIDRIP)
Output []map[string]interface{}
}{
{
Input: []ec2.IPPerm{
ec2.IPPerm{
Protocol: "icmp",
FromPort: 1,
ToPort: -1,
SourceIPs: []string{"0.0.0.0/0"},
SourceGroups: []ec2.UserSecurityGroup{
ec2.UserSecurityGroup{
Id: "sg-11111",
},
},
},
},
Output: []map[string]interface{}{
map[string]interface{}{
"protocol": "icmp",
"from_port": 1,
"to_port": -1,
"cidr_blocks": []string{"0.0.0.0/0"},
"security_groups": []string{"sg-11111"},
},
},
},
{
Input: []ec2.IPPerm{
ec2.IPPerm{
Protocol: "icmp",
FromPort: 1,
ToPort: -1,
SourceIPs: []string{"0.0.0.0/0"},
SourceGroups: nil,
},
},
Output: []map[string]interface{}{
map[string]interface{}{
"protocol": "icmp",
"from_port": 1,
"to_port": -1,
"cidr_blocks": []string{"0.0.0.0/0"},
},
},
},
{
Input: []ec2.IPPerm{
ec2.IPPerm{
Protocol: "icmp",
FromPort: 1,
ToPort: -1,
SourceIPs: nil,
},
},
Output: []map[string]interface{}{
map[string]interface{}{
"protocol": "icmp",
"from_port": 1,
"to_port": -1,
},
},
},
} }
for _, tc := range cases { if *exp.UserIDGroupPairs[0].UserID != *perm.UserIDGroupPairs[0].UserID {
output := flattenIPPerms(tc.Input) t.Fatalf(
if !reflect.DeepEqual(output, tc.Output) { "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
t.Fatalf("Input:\n\n%#v\n\nOutput:\n\n%#v", tc.Input, output) *perm.UserIDGroupPairs[0].UserID,
} *exp.UserIDGroupPairs[0].UserID)
} }
} }
func TestExpandListeners(t *testing.T) { func TestExpandListeners(t *testing.T) {