github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/aws/data_source_aws_security_group.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "log" 6 7 "github.com/aws/aws-sdk-go/aws" 8 "github.com/aws/aws-sdk-go/service/ec2" 9 "github.com/hashicorp/terraform/helper/schema" 10 ) 11 12 func dataSourceAwsSecurityGroup() *schema.Resource { 13 return &schema.Resource{ 14 Read: dataSourceAwsSecurityGroupRead, 15 16 Schema: map[string]*schema.Schema{ 17 "vpc_id": &schema.Schema{ 18 Type: schema.TypeString, 19 Optional: true, 20 Computed: true, 21 }, 22 "name": &schema.Schema{ 23 Type: schema.TypeString, 24 Optional: true, 25 Computed: true, 26 }, 27 "filter": ec2CustomFiltersSchema(), 28 29 "id": &schema.Schema{ 30 Type: schema.TypeString, 31 Optional: true, 32 Computed: true, 33 }, 34 "tags": tagsSchemaComputed(), 35 }, 36 } 37 } 38 39 func dataSourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { 40 conn := meta.(*AWSClient).ec2conn 41 req := &ec2.DescribeSecurityGroupsInput{} 42 43 if id, idExists := d.GetOk("id"); idExists { 44 req.GroupIds = []*string{aws.String(id.(string))} 45 } 46 47 req.Filters = buildEC2AttributeFilterList( 48 map[string]string{ 49 "group-name": d.Get("name").(string), 50 "vpc-id": d.Get("vpc_id").(string), 51 }, 52 ) 53 req.Filters = append(req.Filters, buildEC2TagFilterList( 54 tagsFromMap(d.Get("tags").(map[string]interface{})), 55 )...) 56 req.Filters = append(req.Filters, buildEC2CustomFilterList( 57 d.Get("filter").(*schema.Set), 58 )...) 59 if len(req.Filters) == 0 { 60 // Don't send an empty filters list; the EC2 API won't accept it. 61 req.Filters = nil 62 } 63 64 log.Printf("[DEBUG] Describe Security Groups %v\n", req) 65 resp, err := conn.DescribeSecurityGroups(req) 66 if err != nil { 67 return err 68 } 69 if resp == nil || len(resp.SecurityGroups) == 0 { 70 return fmt.Errorf("no matching SecurityGroup found") 71 } 72 if len(resp.SecurityGroups) > 1 { 73 return fmt.Errorf("multiple Security Groups matched; use additional constraints to reduce matches to a single Security Group") 74 } 75 76 sg := resp.SecurityGroups[0] 77 78 d.SetId(*sg.GroupId) 79 d.Set("id", sg.VpcId) 80 d.Set("name", sg.GroupName) 81 d.Set("description", sg.Description) 82 d.Set("vpc_id", sg.VpcId) 83 d.Set("tags", tagsToMap(sg.Tags)) 84 85 return nil 86 }