forked from hashicorp/terraform-provider-aws
/
data_source_aws_eip.go
62 lines (50 loc) · 1.34 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
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{
"id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"public_ip": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}
func dataSourceAwsEipRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
req := &ec2.DescribeAddressesInput{}
if id, ok := d.GetOk("id"); ok {
req.AllocationIds = []*string{aws.String(id.(string))}
}
if public_ip := d.Get("public_ip"); public_ip != "" {
req.PublicIps = []*string{aws.String(public_ip.(string))}
}
log.Printf("[DEBUG] DescribeAddresses %s\n", req)
resp, err := conn.DescribeAddresses(req)
if err != nil {
return 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]
d.SetId(*eip.AllocationId)
d.Set("public_ip", eip.PublicIp)
return nil
}