Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resource/aws_ec2_capacity_reservation: New resource #6291

Merged
merged 6 commits into from
Oct 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ func Provider() terraform.ResourceProvider {
"aws_dynamodb_table": resourceAwsDynamoDbTable(),
"aws_dynamodb_table_item": resourceAwsDynamoDbTableItem(),
"aws_dynamodb_global_table": resourceAwsDynamoDbGlobalTable(),
"aws_ec2_capacity_reservation": resourceAwsEc2CapacityReservation(),
"aws_ec2_fleet": resourceAwsEc2Fleet(),
"aws_ebs_snapshot": resourceAwsEbsSnapshot(),
"aws_ebs_snapshot_copy": resourceAwsEbsSnapshotCopy(),
Expand Down
270 changes: 270 additions & 0 deletions aws/resource_aws_ec2_capacity_reservation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
package aws

import (
"fmt"
"log"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)

func resourceAwsEc2CapacityReservation() *schema.Resource {
return &schema.Resource{
Create: resourceAwsEc2CapacityReservationCreate,
Read: resourceAwsEc2CapacityReservationRead,
Update: resourceAwsEc2CapacityReservationUpdate,
Delete: resourceAwsEc2CapacityReservationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"availability_zone": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ebs_optimized": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"end_date": {
bflad marked this conversation as resolved.
Show resolved Hide resolved
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRFC3339TimeString,
},
"end_date_type": {
Type: schema.TypeString,
Optional: true,
Default: ec2.EndDateTypeUnlimited,
ValidateFunc: validation.StringInSlice([]string{
ec2.EndDateTypeUnlimited,
ec2.EndDateTypeLimited,
}, false),
},
"ephemeral_storage": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"instance_count": {
Type: schema.TypeInt,
Required: true,
},
"instance_match_criteria": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: ec2.InstanceMatchCriteriaOpen,
ValidateFunc: validation.StringInSlice([]string{
ec2.InstanceMatchCriteriaOpen,
ec2.InstanceMatchCriteriaTargeted,
}, false),
},
"instance_platform": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
ec2.CapacityReservationInstancePlatformLinuxUnix,
ec2.CapacityReservationInstancePlatformRedHatEnterpriseLinux,
ec2.CapacityReservationInstancePlatformSuselinux,
ec2.CapacityReservationInstancePlatformWindows,
ec2.CapacityReservationInstancePlatformWindowswithSqlserver,
ec2.CapacityReservationInstancePlatformWindowswithSqlserverEnterprise,
ec2.CapacityReservationInstancePlatformWindowswithSqlserverStandard,
ec2.CapacityReservationInstancePlatformWindowswithSqlserverWeb,
}, false),
},
"instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"tags": tagsSchema(),
"tenancy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: ec2.CapacityReservationTenancyDefault,
ValidateFunc: validation.StringInSlice([]string{
ec2.CapacityReservationTenancyDefault,
ec2.CapacityReservationTenancyDedicated,
}, false),
},
},
}
}

func resourceAwsEc2CapacityReservationCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn

opts := &ec2.CreateCapacityReservationInput{
AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
InstanceCount: aws.Int64(int64(d.Get("instance_count").(int))),
InstancePlatform: aws.String(d.Get("instance_platform").(string)),
InstanceType: aws.String(d.Get("instance_type").(string)),
}

if v, ok := d.GetOk("ebs_optimized"); ok {
opts.EbsOptimized = aws.Bool(v.(bool))
}

if v, ok := d.GetOk("end_date"); ok {
t, err := time.Parse(time.RFC3339, v.(string))
if err != nil {
return fmt.Errorf("Error parsing EC2 Capacity Reservation end date: %s", err.Error())
}
opts.EndDate = aws.Time(t)
}

if v, ok := d.GetOk("end_date_type"); ok {
opts.EndDateType = aws.String(v.(string))
}

if v, ok := d.GetOk("ephemeral_storage"); ok {
opts.EphemeralStorage = aws.Bool(v.(bool))
}

if v, ok := d.GetOk("instance_match_criteria"); ok {
opts.InstanceMatchCriteria = aws.String(v.(string))
}

if v, ok := d.GetOk("tenancy"); ok {
opts.Tenancy = aws.String(v.(string))
}

if v, ok := d.GetOk("tags"); ok {
tagsSpec := make([]*ec2.TagSpecification, 0)

if len(tagsSpec) > 0 {
tags := tagsFromMap(v.(map[string]interface{}))

spec := &ec2.TagSpecification{
// There is no constant in the SDK for this resource type
ResourceType: aws.String("capacity-reservation"),
Tags: tags,
}

tagsSpec = append(tagsSpec, spec)

opts.TagSpecifications = tagsSpec
}
}

log.Printf("[DEBUG] Capacity reservation: %s", opts)

out, err := conn.CreateCapacityReservation(opts)
if err != nil {
return fmt.Errorf("Error creating EC2 Capacity Reservation: %s", err)
}
d.SetId(*out.CapacityReservation.CapacityReservationId)
return resourceAwsEc2CapacityReservationRead(d, meta)
}

func resourceAwsEc2CapacityReservationRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn

resp, err := conn.DescribeCapacityReservations(&ec2.DescribeCapacityReservationsInput{
CapacityReservationIds: []*string{aws.String(d.Id())},
})

if err != nil {
return fmt.Errorf("Error describing EC2 Capacity Reservations: %s", err)
}

// If nothing was found, then return no state
if len(resp.CapacityReservations) == 0 {
log.Printf("[WARN] EC2 Capacity Reservation (%s) not found, removing from state", d.Id())
d.SetId("")
bflad marked this conversation as resolved.
Show resolved Hide resolved
}

reservation := resp.CapacityReservations[0]

bflad marked this conversation as resolved.
Show resolved Hide resolved
if aws.StringValue(reservation.State) != ec2.CapacityReservationStateCancelled && aws.StringValue(reservation.State) != ec2.CapacityReservationStateExpired {
log.Printf("[WARN] EC2 Capacity Reservation (%s) no longer active, removing from state", d.Id())
d.SetId("")
return nil
}

d.Set("availability_zone", reservation.AvailabilityZone)
d.Set("ebs_optimized", reservation.EbsOptimized)
d.Set("end_date", reservation.EndDate)
d.Set("end_date_type", reservation.EndDateType)
d.Set("ephemeral_storage", reservation.EphemeralStorage)
d.Set("instance_count", reservation.TotalInstanceCount)
d.Set("instance_match_criteria", reservation.InstanceMatchCriteria)
d.Set("instance_platform", reservation.InstancePlatform)
d.Set("instance_type", reservation.InstanceType)
d.Set("tags", tagsToMap(reservation.Tags))
d.Set("tenancy", reservation.Tenancy)

return nil
}

func resourceAwsEc2CapacityReservationUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn

d.Partial(true)

if d.HasChange("tags") {
if err := setTags(conn, d); err != nil {
return err
} else {
d.SetPartial("tags")
}
}

d.Partial(false)

opts := &ec2.ModifyCapacityReservationInput{
CapacityReservationId: aws.String(d.Id()),
}

if d.HasChange("end_date") {
if v, ok := d.GetOk("end_date"); ok {
t, err := time.Parse(time.RFC3339, v.(string))
if err != nil {
return fmt.Errorf("Error parsing EC2 Capacity Reservation end date: %s", err.Error())
}
opts.EndDate = aws.Time(t)
}
}

if d.HasChange("end_date_type") {
opts.EndDateType = aws.String(d.Get("end_date_type").(string))
}

if d.HasChange("instance_count") {
opts.InstanceCount = aws.Int64(int64(d.Get("instance_count").(int)))
}

log.Printf("[DEBUG] Capacity reservation: %s", opts)

_, err := conn.ModifyCapacityReservation(opts)
if err != nil {
return fmt.Errorf("Error modifying EC2 Capacity Reservation: %s", err)
}
return resourceAwsEc2CapacityReservationRead(d, meta)
}

func resourceAwsEc2CapacityReservationDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn

opts := &ec2.CancelCapacityReservationInput{
CapacityReservationId: aws.String(d.Id()),
}

_, err := conn.CancelCapacityReservation(opts)
if err != nil {
return fmt.Errorf("Error cancelling EC2 Capacity Reservation: %s", err)
}

return nil
}
Loading