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

Added resource and data source for aws ec2 capacity block reservation. #37528

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
5602cec
Added resource and data source for aws ec2 capacity block reservation.
prabhavpawar May 14, 2024
6198823
Add changelog
prabhavpawar May 16, 2024
3d1d7fe
Merge branch 'main' into feature/f-aws_ec2_capacity_block-add
johnsonaj Jun 3, 2024
ce01151
aws_ec2_capacity_block_offering: refactor to framework
johnsonaj Jun 4, 2024
c0ca306
aws_ec2_capacity_block_offering: update documentation
johnsonaj Jun 4, 2024
4bfafad
aws_ec2_capacity_block_offering: update documentation
johnsonaj Jun 4, 2024
c79bcbe
aws_ec2_capacity_block_offering: remove testing directive
johnsonaj Jun 4, 2024
77b77bd
fix semgrep errors
johnsonaj Jun 4, 2024
64936e6
aws_ec2_capacity_block_reservation: WIP framework migration
johnsonaj Jun 5, 2024
195ce73
aws_ec2_capacity_block_reservation: migrate to framework
johnsonaj Jun 5, 2024
b58d0e0
chore: semgrep
johnsonaj Jun 6, 2024
70ab38a
chore: fix documentation formatting
johnsonaj Jun 6, 2024
0221a8e
move data source documentation to the correct location
johnsonaj Jun 6, 2024
aa0e053
resolve conflicts
johnsonaj Jun 6, 2024
5695aed
fmt
johnsonaj Jun 6, 2024
c4be0b8
Merge branch 'main' into feature/f-aws_ec2_capacity_block-add
johnsonaj Jun 11, 2024
db7352b
chore: tidy up test names
johnsonaj Jun 11, 2024
58a30ad
aws_ec2_capacity_block_reservation: tidy docs
johnsonaj Jun 11, 2024
bc72e8a
aws_ec2_capacity_block_reservation: add additional attribes to docume…
johnsonaj Jun 11, 2024
f18d457
Merge branch 'main' into feature/f-aws_ec2_capacity_block-add
johnsonaj Jun 11, 2024
a6aa0bc
update CHANGELOG
johnsonaj Jun 11, 2024
51ce353
tidy
johnsonaj Jun 11, 2024
5341a02
aws_ec2_capacity_block_offering: tidy docs
johnsonaj Jun 11, 2024
f347221
aws_ec2_capacity_block_reservation: fix test types
johnsonaj Jun 11, 2024
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
135 changes: 135 additions & 0 deletions internal/service/ec2/ec2_capacity_block_offering_data_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package ec2

import (
"context"
"github.com/hashicorp/terraform-provider-aws/internal/create"
"github.com/hashicorp/terraform-provider-aws/names"
"time"

aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag"
)

const (
ResNameCapacityBlockOffering = "Capacity Block Offering"
)

// @SDKDataSource("aws_ec2_capacity_block_offering")
func DataSourceCapacityBlockOffering() *schema.Resource {
return &schema.Resource{
ReadWithoutTimeout: dataSourceCapacityBlockOfferingRead,
Schema: map[string]*schema.Schema{
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"capacity_duration": {
Type: schema.TypeInt,
Required: true,
},
"currency_code": {
Type: schema.TypeString,
Computed: true,
},
"end_date": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.IsRFC3339Time,
},
"instance_count": {
Type: schema.TypeInt,
Required: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"start_date": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.IsRFC3339Time,
},
"tenancy": {
Type: schema.TypeString,
Computed: true,
},
"upfront_fee": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataSourceCapacityBlockOfferingRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).EC2Conn(ctx)

input := &ec2.DescribeCapacityBlockOfferingsInput{
CapacityDurationHours: aws.Int64(int64(d.Get("capacity_duration").(int))),
InstanceCount: aws.Int64(int64(d.Get("instance_count").(int))),
InstanceType: aws.String(d.Get("instance_type").(string)),
}

if v, ok := d.GetOk("start_date"); ok {
v, _ := time.Parse(time.RFC3339, v.(string))
input.StartDateRange = aws.Time(v)
}

if v, ok := d.GetOk("end_date"); ok {
v, _ := time.Parse(time.RFC3339, v.(string))
input.EndDateRange = aws.Time(v)
}

output, err := conn.DescribeCapacityBlockOfferingsWithContext(ctx, input)

if err != nil {
return create.DiagError(names.EC2, create.ErrActionReading, ResNameCapacityBlockOffering, "unknown", err)
}

if len(output.CapacityBlockOfferings) == 0 {
return diag.Errorf("no %s %s found matching criteria; try different search", names.EC2, ResNameCapacityBlockOffering)
}

if len(output.CapacityBlockOfferings) > 1 {
return diag.Errorf("More than one %s %s found matching criteria; try different search", names.EC2, ResNameCapacityBlockOffering)
}

if err != nil {

return sdkdiag.AppendErrorf(diags, "creating EC2 Capacity Reservation: %s", err)
}

cbo := output.CapacityBlockOfferings[0]
{
d.SetId(aws_sdkv2.ToString(cbo.CapacityBlockOfferingId))
d.Set("availability_zone", cbo.AvailabilityZone)
d.Set("capacity_duration", cbo.CapacityBlockDurationHours)
d.Set("currency_code", cbo.CurrencyCode)
if cbo.EndDate != nil {
d.Set("end_date", aws.TimeValue(cbo.EndDate).Format(time.RFC3339))
} else {
d.Set("end_date", nil)
}
d.Set("instance_count", cbo.InstanceCount)
d.Set("instance_type", cbo.InstanceType)
if cbo.StartDate != nil {
d.Set("start_date", aws.TimeValue(cbo.StartDate).Format(time.RFC3339))
} else {
d.Set("start_date", nil)
}
d.Set("tenancy", cbo.Tenancy)
d.Set("upfront_fee", cbo.UpfrontFee)
}

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package ec2

import (
"fmt"
"testing"
"time"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/names"
)

func TestAccEC2CapacityBlockOffering_basic(t *testing.T) {
ctx := acctest.Context(t)
dataSourceName := "data.aws_ec2_capacity_block_offering.test"
startDate := time.Now().UTC().Add(25 * time.Hour).Format(time.RFC3339)
endDate := time.Now().UTC().Add(720 * time.Hour).Format(time.RFC3339)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(ctx, t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
CheckDestroy: nil,
ErrorCheck: acctest.ErrorCheck(t, names.EC2),
Steps: []resource.TestStep{
{
Config: testAccCapacityBlockOfferingConfig_basic(startDate, endDate),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet(dataSourceName, "availability_zone"),
resource.TestCheckResourceAttr(dataSourceName, "capacity_duration", "24"),
resource.TestCheckResourceAttr(dataSourceName, "instance_count", "1"),
resource.TestCheckResourceAttr(dataSourceName, "instance_type", "p4d.24xlarge"),
resource.TestCheckResourceAttrSet(dataSourceName, "id"),
resource.TestCheckResourceAttr(dataSourceName, "tenancy", "default"),
resource.TestCheckResourceAttrSet(dataSourceName, "upfront_fee"),
),
},
},
})
}

func testAccCapacityBlockOfferingConfig_basic(startDate, endDate string) string {
return fmt.Sprintf(`
data "aws_ec2_capacity_block_offering" "test" {
instance_type = "p4d.24xlarge"
capacity_duration = 24
instance_count = 1
start_date = %[1]q
end_date = %[2]q
}
`, startDate, endDate)
}
130 changes: 130 additions & 0 deletions internal/service/ec2/ec2_capacity_block_reservation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package ec2

import (
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
"github.com/hashicorp/terraform-provider-aws/names"
)

// @SDKResource("aws_ec2_capacity_block_reservation", name="Capacity Block Reservation")
// @Tags(identifierAttribute="id")
func ResourceCapacityBlockReservation() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceCapacityBlockReservationCreate,
ReadWithoutTimeout: resourceCapacityReservationRead,
UpdateWithoutTimeout: schema.NoopContext,
DeleteWithoutTimeout: schema.NoopContext,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},

CustomizeDiff: verify.SetTagsDiff,

Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"capacity_block_offering_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ebs_optimized": {
Type: schema.TypeBool,
Computed: true,
},
"end_date": {
Type: schema.TypeString,
Computed: true,
},
"end_date_type": {
Type: schema.TypeString,
Computed: true,
},
"ephemeral_storage": {
Type: schema.TypeBool,
Computed: true,
},
"instance_count": {
Type: schema.TypeInt,
Computed: true,
},
"instance_match_criteria": {
Type: schema.TypeString,
Computed: true,
},
"instance_platform": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(ec2.CapacityReservationInstancePlatform_Values(), false),
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"outpost_arn": {
Type: schema.TypeString,
Computed: true,
},
"owner_id": {
Type: schema.TypeString,
Computed: true,
},
"placement_group_arn": {
Type: schema.TypeString,
Computed: true,
},
"start_date": {
Type: schema.TypeString,
Computed: true,
},
names.AttrTags: tftags.TagsSchema(),
names.AttrTagsAll: tftags.TagsSchemaComputed(),
"tenancy": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func resourceCapacityBlockReservationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).EC2Conn(ctx)

input := &ec2.PurchaseCapacityBlockInput{
CapacityBlockOfferingId: aws.String(d.Get("capacity_block_offering_id").(string)),
InstancePlatform: aws.String(d.Get("instance_platform").(string)),
TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeCapacityReservation),
}

output, err := conn.PurchaseCapacityBlock(input)

if err != nil {
return sdkdiag.AppendErrorf(diags, "creating EC2 Capacity Reservation: %s", err)
}
d.SetId(aws.StringValue(output.CapacityReservation.CapacityReservationId))

if _, err := WaitCapacityReservationActive(ctx, conn, d.Id()); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for EC2 Capacity Reservation (%s) create: %s", d.Id(), err)
}

return append(diags, resourceCapacityReservationRead(ctx, d, meta)...)
}
Loading