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

Rewire page_rule resource #4695

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
109 changes: 109 additions & 0 deletions internal/services/page_rule/custom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package page_rule

import (
"encoding/json"
"errors"

"github.com/cloudflare/cloudflare-go/v3"
"github.com/cloudflare/cloudflare-go/v3/pagerules"
"github.com/cloudflare/terraform-provider-cloudflare/internal/apijson"
"github.com/hashicorp/terraform-plugin-framework/types"
)

func (m PageRuleModel) marshalCustom() (data []byte, err error) {
if data, err = apijson.MarshalRoot(m); err != nil {
return
}
if data, err = m.marshalTargets(data); err != nil {
return
}
if data, err = m.marshalActions(data); err != nil {
return
}
return
}

func (m PageRuleModel) marshalTargets(b []byte) (data []byte, err error) {
var T struct {
ID string `json:"id,omitempty"`
ZoneID string `json:"zone_id,omitempty"`
Priority int64 `json:"priority,omitempty"`
Status string `json:"status,omitempty"`
CreatedOn string `json:"created_on,omitempty"`
ModifiedOn string `json:"modified_on,omitempty"`
Target string `json:"target,omitempty"`
Targets []any `json:"targets,omitempty"`
}
if err = json.Unmarshal(b, &T); err != nil {
return nil, err
}
T.Targets = []any{
map[string]any{
"target": "url",
"constraint": map[string]any{
"operator": "matches",
"value": T.Target,
},
},
}
T.Target = ""
return json.Marshal(T)
}

func (m PageRuleModel) marshalActions(b []byte) (data []byte, err error) {
var T struct {
ID string `json:"id,omitempty"`
ZoneID string `json:"zone_id,omitempty"`
Priority int64 `json:"priority,omitempty"`
Status string `json:"status,omitempty"`
CreatedOn string `json:"created_on,omitempty"`
ModifiedOn string `json:"modified_on,omitempty"`
Targets []any `json:"targets,omitempty"`
Actions []map[string]any `json:"actions,omitempty"`
}
if err = json.Unmarshal(b, &T); err != nil {
return nil, err
}

T.Actions, err = m.Actions.Encode()
if err != nil {
return nil, err
}

return json.Marshal(T)
}

func (m PageRuleModel) PageruleNewParams() pagerules.PageruleNewParams {
return pagerules.PageruleNewParams{
ZoneID: cloudflare.F(m.ZoneID.ValueString()),
Targets: cloudflare.F([]pagerules.TargetParam{
{
Constraint: cloudflare.F(pagerules.TargetConstraintParam{
Operator: cloudflare.F(pagerules.TargetConstraintOperatorMatches),
Value: cloudflare.F(m.Target.String()),
}),
},
}),
Actions: cloudflare.F([]pagerules.PageruleNewParamsActionUnion{}),
}
}

type PageRuleActionsModel struct {
AutomaticHTTPSRewrites types.String `tfsdk:"automatic_https_rewrites" json:"automatic_https_rewrites,optional"`
DisableApps types.Bool `tfsdk:"disable_apps" json:"disable_apps,optional"`
}

func (m *PageRuleActionsModel) Encode() (encoded []map[string]any, err error) {

switch {
case !m.AutomaticHTTPSRewrites.IsNull():
encoded = append(encoded, map[string]any{"id": pagerules.PageRuleActionsIDAutomaticHTTPSRewrites, "value": m.AutomaticHTTPSRewrites.String()})
case !m.DisableApps.IsNull():
encoded = append(encoded, map[string]any{"id": pagerules.PageRuleActionsIDDisableApps, "value": m.DisableApps.ValueBool()})
default:
// TODO: Throw error for unknown page rule
return nil, errors.New("missing or unknown page rule")
}

return
}
5 changes: 4 additions & 1 deletion internal/services/page_rule/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ type PageRuleModel struct {
Status types.String `tfsdk:"status" json:"status,computed_optional"`
CreatedOn timetypes.RFC3339 `tfsdk:"created_on" json:"created_on,computed" format:"date-time"`
ModifiedOn timetypes.RFC3339 `tfsdk:"modified_on" json:"modified_on,computed" format:"date-time"`

Target types.String `tfsdk:"target" json:"target,required"`
Actions *PageRuleActionsModel `tfsdk:"actions" json:"actions,required"`
}

func (m PageRuleModel) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(m)
return m.marshalCustom()
}

func (m PageRuleModel) MarshalJSONForUpdate(state PageRuleModel) (data []byte, err error) {
Expand Down
4 changes: 1 addition & 3 deletions internal/services/page_rule/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ func (r *PageRuleResource) Create(ctx context.Context, req resource.CreateReques
env := PageRuleResultEnvelope{*data}
_, err = r.client.Pagerules.New(
ctx,
pagerules.PageruleNewParams{
ZoneID: cloudflare.F(data.ZoneID.ValueString()),
},
data.PageruleNewParams(),
option.WithRequestBody("application/json", dataBytes),
option.WithResponseBodyInto(&res),
option.WithMiddleware(logging.Middleware(ctx)),
Expand Down
5 changes: 3 additions & 2 deletions internal/services/page_rule/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,13 @@ func TestAccCloudflarePageRule_Basic(t *testing.T) {
CheckDestroy: testAccCheckCloudflarePageRuleDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckCloudflarePageRuleConfigBasic(zoneID, target, rnd),
// Config: testAccCheckCloudflarePageRuleConfigBasic(zoneID, target, rnd),
Config: buildPageRuleConfig(rnd, zoneID, `disable_apps = true`, target),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudflarePageRuleExists(resourceName, &pageRule),
// testAccCheckCloudflarePageRuleAttributesBasic(&pageRule),
resource.TestCheckResourceAttr(resourceName, consts.ZoneIDSchemaKey, zoneID),
resource.TestCheckResourceAttr(resourceName, "target", fmt.Sprintf("%s/", target)),
resource.TestCheckResourceAttr(resourceName, "target", fmt.Sprintf("%s", target)),
),
},
},
Expand Down
17 changes: 17 additions & 0 deletions internal/services/page_rule/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,23 @@ func ResourceSchema(ctx context.Context) schema.Schema {
Computed: true,
CustomType: timetypes.RFC3339Type{},
},
"target": schema.StringAttribute{
Required: true,
},
"actions": schema.SingleNestedAttribute{
Required: true,
Attributes: map[string]schema.Attribute{
"automatic_https_rewrites": schema.StringAttribute{
Optional: true,
Validators: []validator.String{
stringvalidator.OneOfCaseInsensitive("on", "off"),
},
},
"disable_apps": schema.BoolAttribute{
Optional: true,
},
},
},
},
}
}
Expand Down
15 changes: 7 additions & 8 deletions internal/services/page_rule/testdata/buildpageruleconfig.tf
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@

resource "cloudflare_page_rule" "%[1]s" {
zone_id = "%[2]s"
target = "%[3]s"
actions {
%[4]s
}
}
resource "cloudflare_page_rule" "%[1]s" {
zone_id = "%[2]s"
target = "%[3]s"
actions = {
%[4]s
}
}
Loading