-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
data_source_aws_eip.go
86 lines (69 loc) · 2.06 KB
/
data_source_aws_eip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package aws
import (
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceAwsEip() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsEipRead,
Schema: map[string]*schema.Schema{
"filter": ec2CustomFiltersSchema(),
"id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"public_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"tags": tagsSchemaComputed(),
},
}
}
func dataSourceAwsEipRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
req := &ec2.DescribeAddressesInput{}
if v, ok := d.GetOk("id"); ok {
req.AllocationIds = []*string{aws.String(v.(string))}
}
if v, ok := d.GetOk("public_ip"); ok {
req.PublicIps = []*string{aws.String(v.(string))}
}
req.Filters = []*ec2.Filter{}
req.Filters = append(req.Filters, buildEC2CustomFilterList(
d.Get("filter").(*schema.Set),
)...)
req.Filters = append(req.Filters, buildEC2TagFilterList(
tagsFromMap(d.Get("tags").(map[string]interface{})),
)...)
if len(req.Filters) == 0 {
// Don't send an empty filters list; the EC2 API won't accept it.
req.Filters = nil
}
log.Printf("[DEBUG] Reading EIP: %s", req)
resp, err := conn.DescribeAddresses(req)
if err != nil {
return fmt.Errorf("error describing EC2 Address: %s", err)
}
if resp == nil || len(resp.Addresses) == 0 {
return fmt.Errorf("no matching Elastic IP found")
}
if len(resp.Addresses) > 1 {
return fmt.Errorf("multiple Elastic IPs matched; use additional constraints to reduce matches to a single Elastic IP")
}
eip := resp.Addresses[0]
if aws.StringValue(eip.Domain) == ec2.DomainTypeVpc {
d.SetId(aws.StringValue(eip.AllocationId))
} else {
log.Printf("[DEBUG] Reading EIP, has no AllocationId, this means we have a Classic EIP, the id will also be the public ip : %s", req)
d.SetId(aws.StringValue(eip.PublicIp))
}
d.Set("public_ip", eip.PublicIp)
d.Set("tags", tagsToMap(eip.Tags))
return nil
}