github.com/adrian-bl/terraform@v0.7.0-rc2.0.20160705220747-de0a34fc3517/builtin/providers/aws/import_aws_security_group.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/aws/aws-sdk-go/service/ec2"
     7  	"github.com/hashicorp/terraform/helper/schema"
     8  )
     9  
    10  // Security group import fans out to multiple resources due to the
    11  // security group rules. Instead of creating one resource with nested
    12  // rules, we use the best practices approach of one resource per rule.
    13  func resourceAwsSecurityGroupImportState(
    14  	d *schema.ResourceData,
    15  	meta interface{}) ([]*schema.ResourceData, error) {
    16  	conn := meta.(*AWSClient).ec2conn
    17  
    18  	// First query the security group
    19  	sgRaw, _, err := SGStateRefreshFunc(conn, d.Id())()
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	if sgRaw == nil {
    24  		return nil, fmt.Errorf("security group not found")
    25  	}
    26  	sg := sgRaw.(*ec2.SecurityGroup)
    27  	sgId := d.Id()
    28  
    29  	// Start building our results
    30  	results := make([]*schema.ResourceData, 1,
    31  		1+len(sg.IpPermissions)+len(sg.IpPermissionsEgress))
    32  	results[0] = d
    33  
    34  	// Construct the rules
    35  	ruleResource := resourceAwsSecurityGroupRule()
    36  	permMap := map[string][]*ec2.IpPermission{
    37  		"ingress": sg.IpPermissions,
    38  		"egress":  sg.IpPermissionsEgress,
    39  	}
    40  	for ruleType, perms := range permMap {
    41  		for _, perm := range perms {
    42  			// Construct the rule. We do this by populating the absolute
    43  			// minimum necessary for Refresh on the rule to work. This
    44  			// happens to be a lot of fields since they're almost all needed
    45  			// for de-dupping.
    46  			id := ipPermissionIDHash(sgId, ruleType, perm)
    47  			d := ruleResource.Data(nil)
    48  			d.SetId(id)
    49  			d.SetType("aws_security_group_rule")
    50  			d.Set("security_group_id", sgId)
    51  			d.Set("type", ruleType)
    52  			// XXX If the rule contained more than one source security group, this
    53  			// will choose one of them. We actually need to create one rule for each
    54  			// source security group.
    55  			setFromIPPerm(d, sg, perm)
    56  			results = append(results, d)
    57  		}
    58  	}
    59  
    60  	return results, nil
    61  }