| 1 |
// Copyright 2019 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
//go:build withdeploy |
| 15 |
|
| 16 |
package deploy |
| 17 |
|
| 18 |
import ( |
| 19 |
"context" |
| 20 |
"net/url" |
| 21 |
"time" |
| 22 |
|
| 23 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 24 |
"github.com/aws/aws-sdk-go-v2/service/cloudfront" |
| 25 |
"github.com/aws/aws-sdk-go-v2/service/cloudfront/types" |
| 26 |
"github.com/gohugoio/hugo/deploy/deployconfig" |
| 27 |
gcaws "gocloud.dev/aws" |
| 28 |
) |
| 29 |
|
| 30 |
// V2ConfigFromURLParams will fail for any unknown params, so we need to remove them. |
| 31 |
// This is a mysterious API, but inspecting the code the known params are: |
| 32 |
var v2ConfigValidParams = map[string]bool{ |
| 33 |
"endpoint": true, |
| 34 |
"region": true, |
| 35 |
"profile": true, |
| 36 |
"awssdk": true, |
| 37 |
} |
| 38 |
|
| 39 |
// InvalidateCloudFront invalidates the CloudFront cache for distributionID. |
| 40 |
// Uses AWS credentials config from the bucket URL. |
| 41 |
func InvalidateCloudFront(ctx context.Context, target *deployconfig.Target) error { |
| 42 |
u, err := url.Parse(target.URL) |
| 43 |
if err != nil { |
| 44 |
return err |
| 45 |
} |
| 46 |
vals := u.Query() |
| 47 |
|
| 48 |
// Remove any unknown params. |
| 49 |
for k := range vals { |
| 50 |
if !v2ConfigValidParams[k] { |
| 51 |
vals.Del(k) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
cfg, err := gcaws.V2ConfigFromURLParams(ctx, vals) |
| 56 |
if err != nil { |
| 57 |
return err |
| 58 |
} |
| 59 |
cf := cloudfront.NewFromConfig(cfg) |
| 60 |
req := &cloudfront.CreateInvalidationInput{ |
| 61 |
DistributionId: aws.String(target.CloudFrontDistributionID), |
| 62 |
InvalidationBatch: &types.InvalidationBatch{ |
| 63 |
CallerReference: aws.String(time.Now().Format("20060102150405")), |
| 64 |
Paths: &types.Paths{ |
| 65 |
Items: []string{"/*"}, |
| 66 |
Quantity: aws.Int32(1), |
| 67 |
}, |
| 68 |
}, |
| 69 |
} |
| 70 |
_, err = cf.CreateInvalidation(ctx, req) |
| 71 |
return err |
| 72 |
} |