invalidate.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/aws/aws-sdk-go/aws"
  5. "github.com/aws/aws-sdk-go/aws/credentials"
  6. "github.com/aws/aws-sdk-go/aws/session"
  7. "github.com/aws/aws-sdk-go/service/cloudfront"
  8. "time"
  9. )
  10. func createSession() *cloudfront.CloudFront {
  11. customCreds := credentials.NewStaticCredentials(config.Key, config.Secret, "")
  12. s := session.New(&aws.Config{Credentials: customCreds})
  13. if e, a := customCreds, s.Config.Credentials; e != a {
  14. fmt.Printf("expect %v, got %v\n", e, a)
  15. return nil
  16. }
  17. return cloudfront.New(s)
  18. }
  19. func doViewList() {
  20. svc := createSession()
  21. if svc == nil {
  22. fmt.Println("doViewList createSession failed")
  23. return
  24. }
  25. if err := viewListInvalidations(svc); err != nil {
  26. fmt.Println(err)
  27. }
  28. }
  29. func doInvalidate() bool {
  30. svc := createSession()
  31. if svc == nil {
  32. return false
  33. }
  34. if err := viewListInvalidations(svc); err != nil {
  35. fmt.Println(err)
  36. }
  37. pattern := "/hotfix_asset*"
  38. if config.Pattern != "" {
  39. pattern = config.Pattern
  40. }
  41. if err := createInvalidationRequest(svc, pattern); err != nil {
  42. fmt.Println(err)
  43. return false
  44. }
  45. if err := viewListInvalidations(svc); err != nil {
  46. fmt.Println(err)
  47. }
  48. return true
  49. }
  50. func viewListInvalidations(svc *cloudfront.CloudFront) error {
  51. resp, err := svc.ListInvalidations(&cloudfront.ListInvalidationsInput{
  52. DistributionId: aws.String(config.DistId),
  53. })
  54. if err != nil {
  55. return fmt.Errorf("list.inval. err:%v", err.Error())
  56. }
  57. fmt.Printf("invs:%v\n", resp)
  58. return nil
  59. }
  60. func createInvalidationRequest(svc *cloudfront.CloudFront, pattern string) error {
  61. now := time.Now()
  62. resp, err := svc.CreateInvalidation(&cloudfront.CreateInvalidationInput{
  63. DistributionId: aws.String(config.DistId),
  64. InvalidationBatch: &cloudfront.InvalidationBatch{
  65. CallerReference: aws.String(
  66. fmt.Sprintf("goinvali%s", now.Format("2006/01/02,15:04:05"))),
  67. Paths: &cloudfront.Paths{
  68. Quantity: aws.Int64(1),
  69. Items: []*string{
  70. aws.String(pattern),
  71. },
  72. },
  73. },
  74. })
  75. if err != nil {
  76. return fmt.Errorf("create.inval. err:%v", err.Error())
  77. }
  78. fmt.Printf("invs:%v\n", resp)
  79. return nil
  80. }