terraform/builtin/providers/aws/resource_aws_network_acl.go

365 lines
9.4 KiB
Go
Raw Normal View History

2014-11-26 14:44:02 +01:00
package aws
import (
2014-12-01 09:49:05 +01:00
"bytes"
2014-11-26 14:44:02 +01:00
"fmt"
"log"
"time"
2014-11-26 14:44:02 +01:00
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/ec2"
2014-11-30 12:40:54 +01:00
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
2014-12-01 09:49:05 +01:00
"github.com/hashicorp/terraform/helper/schema"
2014-11-26 14:44:02 +01:00
)
func resourceAwsNetworkAcl() *schema.Resource {
return &schema.Resource{
2014-12-01 09:49:05 +01:00
Create: resourceAwsNetworkAclCreate,
Read: resourceAwsNetworkAclRead,
Delete: resourceAwsNetworkAclDelete,
Update: resourceAwsNetworkAclUpdate,
2014-11-26 14:44:02 +01:00
Schema: map[string]*schema.Schema{
"vpc_id": &schema.Schema{
Type: schema.TypeString,
2014-12-03 08:53:18 +01:00
Required: true,
2014-11-26 14:44:02 +01:00
ForceNew: true,
2014-12-03 08:53:18 +01:00
Computed: false,
2014-11-26 14:44:02 +01:00
},
2014-11-30 12:40:54 +01:00
"subnet_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
2014-12-03 08:53:18 +01:00
Computed: false,
2014-11-30 12:40:54 +01:00
},
"ingress": &schema.Schema{
Type: schema.TypeSet,
Required: false,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"from_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"to_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"rule_no": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"action": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"cidr_block": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
Set: resourceAwsNetworkAclEntryHash,
},
"egress": &schema.Schema{
Type: schema.TypeSet,
Required: false,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"from_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"to_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"rule_no": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"action": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"cidr_block": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
Set: resourceAwsNetworkAclEntryHash,
2014-12-01 09:49:05 +01:00
},
2014-12-10 11:59:00 +01:00
"tags": tagsSchema(),
2014-11-26 14:44:02 +01:00
},
}
}
func resourceAwsNetworkAclCreate(d *schema.ResourceData, meta interface{}) error {
2014-12-01 09:49:05 +01:00
2015-03-13 15:42:50 +01:00
ec2conn := meta.(*AWSClient).ec2conn
2014-11-26 14:44:02 +01:00
// Create the Network Acl
createOpts := &ec2.CreateNetworkACLRequest{
VPCID: aws.String(d.Get("vpc_id").(string)),
2014-11-26 14:44:02 +01:00
}
2014-11-26 14:44:02 +01:00
log.Printf("[DEBUG] Network Acl create config: %#v", createOpts)
resp, err := ec2conn.CreateNetworkACL(createOpts)
2014-11-26 14:44:02 +01:00
if err != nil {
return fmt.Errorf("Error creating network acl: %s", err)
}
// Get the ID and store it
networkAcl := resp.NetworkACL
d.SetId(*networkAcl.NetworkACLID)
log.Printf("[INFO] Network Acl ID: %s", *networkAcl.NetworkACLID)
2014-11-26 14:44:02 +01:00
// Update rules and subnet association once acl is created
2014-11-30 12:40:54 +01:00
return resourceAwsNetworkAclUpdate(d, meta)
2014-11-26 14:44:02 +01:00
}
func resourceAwsNetworkAclRead(d *schema.ResourceData, meta interface{}) error {
2015-03-13 15:42:50 +01:00
ec2conn := meta.(*AWSClient).ec2conn
2014-11-26 14:44:02 +01:00
resp, err := ec2conn.DescribeNetworkACLs(&ec2.DescribeNetworkACLsRequest{
NetworkACLIDs: []string{d.Id()},
})
2014-11-26 14:44:02 +01:00
if err != nil {
return err
}
if resp == nil {
return nil
}
networkAcl := &resp.NetworkACLs[0]
var ingressEntries []ec2.NetworkACLEntry
var egressEntries []ec2.NetworkACLEntry
2014-11-26 14:44:02 +01:00
// separate the ingress and egress rules
for _, e := range networkAcl.Entries {
if *e.Egress == true {
2014-11-30 12:40:54 +01:00
egressEntries = append(egressEntries, e)
2014-12-01 09:49:05 +01:00
} else {
2014-11-30 12:40:54 +01:00
ingressEntries = append(ingressEntries, e)
}
}
d.Set("vpc_id", networkAcl.VPCID)
2014-11-30 12:40:54 +01:00
d.Set("ingress", ingressEntries)
d.Set("egress", egressEntries)
d.Set("tags", tagsToMap(networkAcl.Tags))
2014-11-30 12:40:54 +01:00
2014-11-26 14:44:02 +01:00
return nil
}
func resourceAwsNetworkAclUpdate(d *schema.ResourceData, meta interface{}) error {
2015-03-13 15:42:50 +01:00
ec2conn := meta.(*AWSClient).ec2conn
2014-11-30 12:40:54 +01:00
d.Partial(true)
2014-12-01 09:49:05 +01:00
if d.HasChange("ingress") {
2014-11-30 12:40:54 +01:00
err := updateNetworkAclEntries(d, "ingress", ec2conn)
2014-12-01 09:49:05 +01:00
if err != nil {
2014-11-30 12:40:54 +01:00
return err
}
}
2014-12-01 09:49:05 +01:00
if d.HasChange("egress") {
2014-11-30 12:40:54 +01:00
err := updateNetworkAclEntries(d, "egress", ec2conn)
2014-12-01 09:49:05 +01:00
if err != nil {
2014-11-30 12:40:54 +01:00
return err
}
}
2014-12-03 08:53:18 +01:00
if d.HasChange("subnet_id") {
//associate new subnet with the acl.
_, n := d.GetChange("subnet_id")
newSubnet := n.(string)
association, err := findNetworkAclAssociation(newSubnet, ec2conn)
if err != nil {
return fmt.Errorf("Failed to update acl %s with subnet %s: %s", d.Id(), newSubnet, err)
}
_, err = ec2conn.ReplaceNetworkACLAssociation(&ec2.ReplaceNetworkACLAssociationRequest{
AssociationID: association.NetworkACLAssociationID,
NetworkACLID: aws.String(d.Id()),
})
if err != nil {
return err
}
}
if err := setTags(ec2conn, d); err != nil {
2014-12-10 11:59:00 +01:00
return err
} else {
d.SetPartial("tags")
}
2014-11-30 12:40:54 +01:00
d.Partial(false)
2014-11-26 14:44:02 +01:00
return resourceAwsNetworkAclRead(d, meta)
2014-11-30 12:40:54 +01:00
}
2014-12-01 09:49:05 +01:00
func updateNetworkAclEntries(d *schema.ResourceData, entryType string, ec2conn *ec2.EC2) error {
2014-11-30 12:40:54 +01:00
o, n := d.GetChange(entryType)
if o == nil {
o = new(schema.Set)
}
if n == nil {
n = new(schema.Set)
}
os := o.(*schema.Set)
ns := n.(*schema.Set)
toBeDeleted, err := expandNetworkAclEntries(os.Difference(ns).List(), entryType)
if err != nil {
return err
}
2014-11-30 12:40:54 +01:00
for _, remove := range toBeDeleted {
// Delete old Acl
err := ec2conn.DeleteNetworkACLEntry(&ec2.DeleteNetworkACLEntryRequest{
NetworkACLID: aws.String(d.Id()),
RuleNumber: remove.RuleNumber,
Egress: remove.Egress,
})
2014-12-01 09:49:05 +01:00
if err != nil {
return fmt.Errorf("Error deleting %s entry: %s", entryType, err)
}
2014-11-30 12:40:54 +01:00
}
toBeCreated, err := expandNetworkAclEntries(ns.Difference(os).List(), entryType)
if err != nil {
return err
}
2014-11-30 12:40:54 +01:00
for _, add := range toBeCreated {
// Add new Acl entry
err := ec2conn.CreateNetworkACLEntry(&ec2.CreateNetworkACLEntryRequest{
NetworkACLID: aws.String(d.Id()),
CIDRBlock: add.CIDRBlock,
Egress: add.Egress,
PortRange: add.PortRange,
Protocol: add.Protocol,
RuleAction: add.RuleAction,
RuleNumber: add.RuleNumber,
})
2014-12-01 09:49:05 +01:00
if err != nil {
return fmt.Errorf("Error creating %s entry: %s", entryType, err)
}
2014-11-30 12:40:54 +01:00
}
return nil
2014-11-26 14:44:02 +01:00
}
func resourceAwsNetworkAclDelete(d *schema.ResourceData, meta interface{}) error {
2015-03-13 15:42:50 +01:00
ec2conn := meta.(*AWSClient).ec2conn
2014-11-26 14:44:02 +01:00
log.Printf("[INFO] Deleting Network Acl: %s", d.Id())
return resource.Retry(5*time.Minute, func() error {
err := ec2conn.DeleteNetworkACL(&ec2.DeleteNetworkACLRequest{
NetworkACLID: aws.String(d.Id()),
})
if err != nil {
ec2err := err.(aws.APIError)
switch ec2err.Code {
2014-12-03 08:53:18 +01:00
case "InvalidNetworkAclID.NotFound":
return nil
case "DependencyViolation":
// In case of dependency violation, we remove the association between subnet and network acl.
// This means the subnet is attached to default acl of vpc.
association, err := findNetworkAclAssociation(d.Get("subnet_id").(string), ec2conn)
if err != nil {
return fmt.Errorf("Dependency violation: Cannot delete acl %s: %s", d.Id(), err)
2014-12-03 08:53:18 +01:00
}
defaultAcl, err := getDefaultNetworkAcl(d.Get("vpc_id").(string), ec2conn)
if err != nil {
return fmt.Errorf("Dependency violation: Cannot delete acl %s: %s", d.Id(), err)
2014-12-03 08:53:18 +01:00
}
_, err = ec2conn.ReplaceNetworkACLAssociation(&ec2.ReplaceNetworkACLAssociationRequest{
AssociationID: association.NetworkACLAssociationID,
NetworkACLID: defaultAcl.NetworkACLID,
})
return resource.RetryError{Err: err}
2014-12-03 08:53:18 +01:00
default:
// Any other error, we want to quit the retry loop immediately
return resource.RetryError{Err: err}
}
2014-11-26 14:44:02 +01:00
}
2014-12-03 08:53:18 +01:00
log.Printf("[Info] Deleted network ACL %s successfully", d.Id())
return nil
})
2014-11-26 14:44:02 +01:00
}
2014-11-30 12:40:54 +01:00
func resourceAwsNetworkAclEntryHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%d-", m["from_port"].(int)))
buf.WriteString(fmt.Sprintf("%d-", m["to_port"].(int)))
2014-11-30 12:40:54 +01:00
buf.WriteString(fmt.Sprintf("%d-", m["rule_no"].(int)))
buf.WriteString(fmt.Sprintf("%s-", m["action"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cidr_block"].(string)))
if v, ok := m["ssl_certificate_id"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
return hashcode.String(buf.String())
}
func getDefaultNetworkAcl(vpc_id string, ec2conn *ec2.EC2) (defaultAcl *ec2.NetworkACL, err error) {
resp, err := ec2conn.DescribeNetworkACLs(&ec2.DescribeNetworkACLsRequest{
NetworkACLIDs: []string{},
Filters: []ec2.Filter{
ec2.Filter{
Name: aws.String("default"),
Values: []string{"true"},
},
ec2.Filter{
Name: aws.String("vpc-id"),
Values: []string{vpc_id},
},
},
})
if err != nil {
return nil, err
}
return &resp.NetworkACLs[0], nil
2014-12-03 08:53:18 +01:00
}
func findNetworkAclAssociation(subnetId string, ec2conn *ec2.EC2) (networkAclAssociation *ec2.NetworkACLAssociation, err error) {
resp, err := ec2conn.DescribeNetworkACLs(&ec2.DescribeNetworkACLsRequest{
NetworkACLIDs: []string{},
Filters: []ec2.Filter{
ec2.Filter{
Name: aws.String("association.subnet-id"),
Values: []string{subnetId},
},
},
})
if err != nil {
return nil, err
}
for _, association := range resp.NetworkACLs[0].Associations {
if *association.SubnetID == subnetId {
2014-12-03 08:53:18 +01:00
return &association, nil
}
}
return nil, fmt.Errorf("could not find association for subnet %s ", subnetId)
}