setTimeout( () => {
      // If production invalidate cloudfront
      if( process.env.NODE_ENV == "production" && env.cloudfrontID != "" ){
        let cloudfront = new AWS.CloudFront({apiVersion: '2017-03-25'});
        var params = {
          DistributionId: env.cloudfrontID,
          InvalidationBatch: { 
            CallerReference: Math.random() + '', 
            Paths: { 
              Quantity: 1,
              Items: [
                '/*',
              ]
            }
          }
        };

        // Invalidate cloudfront
        cloudfront.createInvalidation(params, function(err, data) {
          if (err) console.log(err, err.stack); // an error occurred
          else     console.log(data);           // successful response
        });
      }

      // Live message
      console.log("Site now live at: " + env.bucket + ".s3-website-" + env.region + ".amazonaws.com");
    },5500)
    return function() {
        console.log('Invalidating hashes.json & loader');

        var params = {
            DistributionId: process.env.BAMBOO_CDNDISTRIBUTIONID,
            InvalidationBatch: {
                CallerReference: 'deploy-' + Math.random(),
                Paths: {
                    Quantity: 2,
                    Items: ['/hashes.json', '/js/vendor/vendor.json', '/js/loader.min.js']
                }
            }
        };

        var cloudfront = new aws.CloudFront({
            accessKeyId: process.env.BAMBOO_AWSKEY,
            secretAccessKey: process.env.BAMBOO_AWSSECRET,
            region: process.env.BAMBOO_CDNREGION,
        });

        cloudfront.createInvalidation(params, function (err, data) {

            if (err)
                console.log(err, err.stack);

            cb();

        });
    }
Example #3
0
  grunt.registerMultiTask('cloudfront', 'Cloudfront cache invalidating task', function() {
    var done = this.async(),
        options = this.options(),
        paths = this.data.paths;

    AWS.config.update({ region: options.region });

    if (options.credentials) {
      AWS.config.update({
        accessKeyId:     options.credentials.accessKeyId,
        secretAccessKey: options.credentials.secretAccessKey
      });
    } else {
      AWS.config.update({
        accessKeyId:     process.env['AWS_ACCESS_KEY_ID'],
        secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY']
      });
    }

    var CloudFront = new AWS.CloudFront();

    CloudFront.createInvalidation({
      DistributionId:    options.distributionId,
      InvalidationBatch: {
        'Paths': {
          'Quantity': paths.length,
          'Items': paths
        },
        'CallerReference': (new Date()).getTime().toString()
      }
    }, function (err, data) {
      if (err) {
        grunt.log.error("Invalidation failed : "+err.message);
        return done(false);
      }

      grunt.log.write("Invalidation succeeded. Please wait a few minutes for propagation.").ok();
      console.log(inspect(data));

      if (options.listInvalidations) {
        CloudFront.listInvalidations({
          DistributionId: options.distributionId
        }, function (err, data) {
          if (err) {
            grunt.log.errorlns(inspect(err));
          } else {
            grunt.log.writeln(inspect(data));
          }
          done();
        });
      } else {
        done();
      }
    });
  });
  var invalidate = function(callback){
    if(files.length == 0) return callback();

    files = files.map(function(file) {
      return '/' + file;
    });

    cloudfront.createInvalidation({
      DistributionId: options.distribution,
      InvalidationBatch: {
        CallerReference: Date.now().toString(),
        Paths: {
          Quantity: files.length,
          Items: files
        }
      }
    }, function (err, res) {
      if (err) return complain(err, 'Could not invalidate cloudfront', callback);

      util.log('Cloudfront invalidation created: ' + res.Invalidation.Id);

      if (!options.wait) {
        return callback();
      }

      check(res.Invalidation.Id, callback);
    });
  }
Example #5
0
      cloudfront.getDistribution({ Id: opts.distributionId }, function(err, res) {
        if (err) {
          console.log(err, err.stack);
          return callback(err);
        }

        var params = {
          Id: opts.distributionId,
          DistributionConfig: res.Distribution.DistributionConfig,
          IfMatch: res.ETag
        };

        if(opts.customErrorResponses){
          params.DistributionConfig.CustomErrorResponses = {
            Quantity: opts.customErrorResponses.length,
            Items: opts.customErrorResponses
          };
        }

        if(opts.originPath){
          params.DistributionConfig.Origins.Items[ 0 ].OriginPath = opts.originPath;
        }

        if(opts.defaultRootObject){
          params.DistributionConfig.DefaultRootObject = opts.defaultRootObject;
        }

        cloudfront.updateDistribution(params, function(err, data) {
          if (err) console.log(err, err.stack);
          else console.log(data);
          callback(err);
        });
      });
Example #6
0
        cloudfront.getDistribution({ Id: options.distributionId }, function(err, data) {

            if (err) {                
                deferred.reject(err);
            } else {

                // AWS Service returns errors if we don't fix these
                if (data.DistributionConfig.Comment == null) data.DistributionConfig.Comment = '';
                if (data.DistributionConfig.Logging.Enabled == false) {
                    data.DistributionConfig.Logging.Bucket = '';
                    data.DistributionConfig.Logging.Prefix = '';
                }
                if (data.DistributionConfig.Origins.Items[0]) {
                	data.DistributionConfig.Origins.Items[0].S3OriginConfig.OriginAccessIdentity = '';
                }

                // Update the distribution with the new default root object
                data.DistributionConfig.DefaultRootObject = defaultRootObject;
                cloudfront.updateDistribution({
                    IfMatch: data.ETag,
                    Id: options.distributionId,
                    DistributionConfig: data.DistributionConfig
                }, function(err, data) {

                    if (err) {                
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }

                });

            }
        });   
 /**
  * Function: invalidate
  * 
  * Invalidates objects on cloudfront.
  * 
  * Parameters:
  *  dist - Cloudfront distribution ID
  *  paths - An array of pathnames to invalidate
  *  options - Options object
  *      wait - If true, wait until the invalidation is complete.
  *      secretKeyId - If set, use this as the AWS key ID
  *      secretAccessKey - The AWS secret key
  *  callback - Callback
  */
 function invalidate(dist, paths, options, callback) {
     
     if (options.secretKeyId) {
         cloudfront.config.update({
             secretKeyId: options.secretKeyId,
             secretAccessKey: options.secretAccessKey,
         });
     }
     
     paths = paths.map(function (v) {
         if (v.charAt(0) === "/") {
             return v;
         } else {
             return "/" + v;
         }
     });
     
     var callerReference = "cf-invalidate-" + Date.now() + "_" + randomDigits();
     
     cloudfront.createInvalidation({
         DistributionId: dist,
         InvalidationBatch: {
             CallerReference: callerReference,
             Paths: {
                 Quantity: paths.length,
                 Items: paths,
             },
         },
     }, function (err, res) {
         if (err) {return callback(err);}
         
         var invalidationId = res.Invalidation.Id;
         if (options.wait) {
             
             var iteration = function () {
                 cloudfront.getInvalidation({
                     DistributionId: dist,
                     Id: invalidationId
                 }, function (err, res) {
                     if (err) {return callback(err);}
                     
                     if (res.Invalidation.Status === "Completed") {
                         return callback();
                     } else {
                         setTimeout(function () {
                             iteration();
                         }, 1000);
                     }
                     
                 });
             };
             iteration();
             
         } else {
             callback();
         }
         
     });
     
 }
 }, function(err, data) {
   if(err) {
     grunt.log.error("Invalidation failed : "+err.message);
     done(false);
   }
   else {
     grunt.log.write("Invalidation succeeded. Please wait a few minutes.").ok();
     console.log(data);
     if(options.listInvalidations) {
       CloudFront.listInvalidations({
           DistributionId:options.distributionId
         },
         function(err, data) {
           if(err) {
             grunt.log.errorlns(util.inspect(err));
           }
           else {
             grunt.log.writeln(util.inspect(data));
           }
           done();
       });
     }
     else {
       done();
     }
   }
 });
        function (req, next) {
            if (req.config.target.cloudfront) {
                console.log('creating cloudfront invalidation');

                var cloudfront = new AWS.CloudFront({
                    region: req.config.target.region,
                    accessKeyId: req.config.target.accessKeyId ,
                    secretAccessKey: req.config.target.secretAccessKey
                });

                cloudfront.createInvalidation({
                    DistributionId: req.config.target.cloudfront.distribution,
                    InvalidationBatch: {
                        CallerReference: `contentful-webhook-${new Date().getTime()}-${parseInt(Math.random() * 10e8)}`,
                        Paths: {
                            Quantity: 1,
                            Items: [ `/*` ]
                        }
                    }
                }, function (err, data) {
                    if (err) {
                        next(`failed: ${err}`)
                    }
                    else {
                        console.log('... created');
                        next(null, {
                            ok: true,
                            bucket: req.bucket,
                            key: req.key,
                            invalidation: data.Invalidation.Id
                        })
                    }
                })
            }
            else {
                next(null, {
                    ok: true,
                    bucket: req.bucket,
                    key: req.key
                });
            }
        }
 // Creates the invalidation for the distribution that uses the bucket as a origin.
 function createInvalidation(params, deferred) {
     cloudfront.createInvalidation(params, function (error, data) {
         if (error) {
             console.log('Got error creating the invalidation: ' + JSON.stringify(error, true, '  '));
             deferred.reject();
             return;
         }
         console.log('Success: ' + JSON.stringify(data.InvalidationBatch, true, '  '));
         deferred.resolve();
     });
 }
Example #11
0
 return new Promise((resolve, reject) => {
   cf.createInvalidation({
     DistributionId: config.cloudfrontID,
     InvalidationBatch: {
       CallerReference: (new Date()).toISOString(),
       Paths: {
         Quantity: paths.length,
         Items: paths
       }
     }
   }, err => err ? reject(err) : resolve())
 })
  function endStream(cb) {
    AWS.config.update({
      region: options.region,
      accessKeyId: (process.env.AWS_ACCESS_KEY_ID ||
                    options.credentials.accessKeyId),
      secretAccessKey: (process.env.AWS_SECRET_ACCESS_KEY ||
                        options.credentials.secretAccessKey)
    });

    var cloudfront = new AWS.CloudFront();
    cloudfront.createInvalidation({
      DistributionId: options.distributionId,
      InvalidationBatch: invalidationBatch
    }, function(err, data) {
      if (err) {
        throw new gutil.PluginError('gulp-invalidate-cloudfront', 'Could not invalidate cloudfront: ' + err);
        return cb(false);
      }

      gutil.log('Cloudfront invalidation created with id: ' + data.Invalidation.Id);
      cb();
    });
  }
Example #13
0
    return new Promise(function(resolve, reject) {
      if (cloudfrontInvalidateOptions.DistributionId) {
        var cloudfront = new aws.CloudFront()

        cloudfront.config.update({
          accessKeyId: clientConfig.s3Options.accessKeyId,
          secretAccessKey: clientConfig.s3Options.secretAccessKey,
        })

        cloudfront.createInvalidation({
          DistributionId: cloudfrontInvalidateOptions.DistributionId,
          InvalidationBatch: {
            CallerReference: Date.now().toString(),
            Paths: {
              Quantity: cloudfrontInvalidateOptions.Items.length,
              Items: cloudfrontInvalidateOptions.Items
            }
          }
        }, (err, res) => err ? reject(err) : resolve(res.Id))
      } else {
        return resolve(null)
      }
    })
Example #14
0
  list: function(old_cert_id, lib_cb) {
    cloudfront.listDistributions(function(cf_error, distributions) {
      if (cf_error) {
        return lib_cb(cf_error);
      }

      var distributions_to_update = distributions.DistributionList.Items.filter(function(d) {
        return d.ViewerCertificate.IAMCertificateId === old_cert_id;
      }).map(function(d) {
        return d.Id;
      });

      lib_cb(null, distributions_to_update);
    });
  },
  var check = function (id, callback) {
    cloudfront.getInvalidation({
      DistributionId: options.distribution,
      Id: id
    }, function (err, res) {
      if (err) return complain(err, 'Could not check on invalidation', callback);

      if (res.Invalidation.Status === 'Completed') {
        return callback();
      } else {
        setTimeout(function () {
          check(id, callback);
        }, 1000);
      }
    })
  };
 var iteration = function () {
     cloudfront.getInvalidation({
         DistributionId: dist,
         Id: invalidationId
     }, function (err, res) {
         if (err) {return callback(err);}
         
         if (res.Invalidation.Status === "Completed") {
             return callback();
         } else {
             setTimeout(function () {
                 iteration();
             }, 1000);
         }
         
     });
 };
Example #17
0
 function createInvalidations(callback) {
   var params = {
     DistributionId: opts.distributionId,
     InvalidationBatch: {
       CallerReference: Date.now().toString(),
       Paths: {
         Quantity: opts.invalidations.length,
         Items: opts.invalidations
       }
     }
   };
   cloudfront.createInvalidation(params, function(err, data) {
     if (err) console.log(err, err.stack);
     else console.log(data);
     callback(err);
   });
 }
Example #18
0
  grunt.registerMultiTask("cloudfront", DESC, function() {

    //get options
    var opts = this.options(DEFAULTS);

    if(_.isEmpty(opts.distributionId))
      return grunt.log.ok("No DistributionId specified");    

    if(_.isEmpty(opts.invalidations))
      return grunt.log.ok("No invalidations specified");

    //mark as async
    var done = this.async();

    //whitelist allowed keys
    AWS.config.update(_.pick(opts,
      'accessKeyId',
      'secretAccessKey'
    ), true);
 
    //cloudfront client
    var cloudfront = new AWS.CloudFront();

    //create records defined in opts.invalidations
    createInvalidations(done);

    //------------------------------------------------

    function createInvalidations(callback) {
      var params = {
        DistributionId: opts.distributionId,
        InvalidationBatch: {
          CallerReference: Date.now().toString(),
          Paths: {
            Quantity: opts.invalidations.length,
            Items: opts.invalidations
          }
        }
      };
      cloudfront.createInvalidation(params, function(err, data) {
        if (err) console.log(err, err.stack);
        else console.log(data);
        callback(err);
      });
    }
  });
Example #19
0
    var invalidateCache = function(items) {
			cloudfront.createInvalidation({
	      DistributionId: options.distributionId,
	      InvalidationBatch: {
	      	CallerReference: Date.now().toString(),
		      Paths: {
		        Quantity: items.length,
		        Items: items
		      }
		    }
	    }, function(err, data) {
	      if(err) {
	        gutil.log("Invalidation failed: ", err);
	      }
	      else {
	        gutil.log("Invalidation request successful - takes a few minutes to complete.");
	      }
			});
		};
function createInvalidation(DistributionId, CallerReference, records, callback){
    let _items = records.map((rec) => {
        return '/' + rec.s3.object.key;
    });
    let _params = {
        DistributionId: DistributionId,
        InvalidationBatch: {
            CallerReference: CallerReference,
            Paths: {
                Quantity: _items.length,
                Items: _items
            }
        }
    };
    cloudfront.createInvalidation(_params, function(err, data) {
        if (err) callback(err);
        else callback();
    });
}
Example #21
0
 return new Promise(function(resolve, reject) {
     cloudfront.createInvalidation(
         {
             DistributionId: id,
             InvalidationBatch: {
                 CallerReference: time + id,
                 Paths: {
                     Quantity: 1,
                     Items: ["/*"]
                 }
             }
         },
         function(err, data) {
             if (err) {
                 reject(err);
                 return;
             }
             resolve(data);
         }
     );
 });
Example #22
0
      distribution.Origins.Items.map(function (origin) {
        if (exists) return;

        console.log(origin.DomainName, bucket);

        if (origin.DomainName.indexOf(bucket) === 0) {
          exists = true;
          var name = distribution.DomainName;
          if (distribution.Aliases.Quantity > 0) {
            name = distribution.Aliases.Items[0];
          }
          console.log('Distribution: ' + distribution.Id + ' ('+ name + ')');

          // Parameters for a invalidation
          var params = {
            DistributionId : distribution.Id,
            InvalidationBatch : {
              CallerReference : '' + new Date().getTime(),
              Paths : {
                Quantity : 1,
                Items : [ '/'+key ]
              }
            }
          };
          _log('Params: ', params);

          // Invalidate
          cloudfront.createInvalidation(params, function (err, data) {
            if (err) {
              _log('Error: ', err);
              deferred.reject();
              return;
            }
            _log('Success: ', data.InvalidationBatch);
            deferred.resolve();
          });
        }
      });
  grunt.registerMultiTask('cloudfront', 'Cloudfront cache invalidating task', function() {
    var done = this.async(),
        options = this.options(),
        version = options.version;

    AWS.config.update({
      region:options.region,
      accessKeyId: options.credentials.accessKeyId,
      secretAccessKey: options.credentials.secretAccessKey
    });
    var CloudFront = new AWS.CloudFront();

    if(!_.isUndefined(version)) {
      grunt.log.writeln("Version number detected. Changing "+this.data.Paths.Items.length+" filenames.");
      _.each(this.data.Paths.Items, function(file, i, files) {

        var lastDot = file.lastIndexOf('.'),
            extension = file.slice(lastDot,file.length),
            fileName = file.slice(0, lastDot),
            newFileName = fileName+"-"+version+extension;

          grunt.log.writeln(fileName + " -> " + newFileName);
      });
    }

    CloudFront.createInvalidation({
      DistributionId:options.distributionId,
      InvalidationBatch:this.data
    }, function(err, data) {
      if(err) {
        grunt.log.error("Invalidation failed : "+err.message);
        done(false);
      }
      else {
        grunt.log.write("Invalidation succeeded. Please wait a few minutes.").ok();
        console.log(data);
        if(options.listInvalidations) {
          CloudFront.listInvalidations({
              DistributionId:options.distributionId
            },
            function(err, data) {
              if(err) {
                grunt.log.errorlns(util.inspect(err));
              }
              else {
                grunt.log.writeln(util.inspect(data));
              }
              done();
          });
        }
        else {
          done();
        }
      }
    });
    if(options.listDistributions) {
      CloudFront.listDistributions({},function(err, data) {
        if(err) {
          grunt.log.errorlns(err);
          done(false);
        }
        else {
          var distributions = data.Items;
          for(var i=0;i<distributions.length;i++) {
            grunt.log.writeln(util.inspect(distributions[i]));
          }
          done();
        }
      });
    }
    
  });
(function () {
    "use strict";
    
    
    
    var usageString =
        "cf-invalidate [--wait] [--secretKeyId <keyId> --secretAccessKey <key>] -- <distribution> <path>...";
    var exampleString =
        "cf-invalidate -- myDistribution file1 file2 file3";
    
    var AWS = require("aws-sdk");
    var yargs = require("yargs");
    
    var cloudfront = new AWS.CloudFront();
    var log = function () {};
    var error = function () {};
    
    
    
    
    /**
     * Function: randomDigits
     * 
     * Returns a random string of 4 digits.
     */
    function randomDigits() {
        var n = Math.floor(Math.random() * 1000);
        return "" + ({
            "0": "0000",
            "1": "000",
            "2": "00",
            "3": "0",
            "4": "",
        }[("" + n).length]) + n;
    }
    
    
    
    
    /**
     * Function: invalidate
     * 
     * Invalidates objects on cloudfront.
     * 
     * Parameters:
     *  dist - Cloudfront distribution ID
     *  paths - An array of pathnames to invalidate
     *  options - Options object
     *      wait - If true, wait until the invalidation is complete.
     *      secretKeyId - If set, use this as the AWS key ID
     *      secretAccessKey - The AWS secret key
     *  callback - Callback
     */
    function invalidate(dist, paths, options, callback) {
        
        if (options.secretKeyId) {
            cloudfront.config.update({
                secretKeyId: options.secretKeyId,
                secretAccessKey: options.secretAccessKey,
            });
        }
        
        paths = paths.map(function (v) {
            if (v.charAt(0) === "/") {
                return v;
            } else {
                return "/" + v;
            }
        });
        
        var callerReference = "cf-invalidate-" + Date.now() + "_" + randomDigits();
        
        cloudfront.createInvalidation({
            DistributionId: dist,
            InvalidationBatch: {
                CallerReference: callerReference,
                Paths: {
                    Quantity: paths.length,
                    Items: paths,
                },
            },
        }, function (err, res) {
            if (err) {return callback(err);}
            
            var invalidationId = res.Invalidation.Id;
            if (options.wait) {
                
                var iteration = function () {
                    cloudfront.getInvalidation({
                        DistributionId: dist,
                        Id: invalidationId
                    }, function (err, res) {
                        if (err) {return callback(err);}
                        
                        if (res.Invalidation.Status === "Completed") {
                            return callback();
                        } else {
                            setTimeout(function () {
                                iteration();
                            }, 1000);
                        }
                        
                    });
                };
                iteration();
                
            } else {
                callback();
            }
            
        });
        
    }
    
    
    
    
    
    
    
    
    if (module === require.main) {
        log = console.log.bind(console);
        error = console.error.bind(console);
        var argv = yargs
            .usage(usageString)
            .example(exampleString)
            .demand(2)
            .option("secretKeyId", {
                alias: "i",
                describe: "AWS Key Id override",
            })
            .option("secretAccessKey", {
                alias: "k",
                describe: "AWS Secret Key override",
            })
            .implies("secretKeyId", "secretAccessKey")
            .implies("secretAccessKey", "secretKeyId")
            .option("wait", {
                alias: "w",
                describe: "If set, wait til the invalidation completes",
            })
            .argv;
        invalidate(argv._[0], argv._.slice(1), argv, function (err) {
            if (err) {
                error(err);
                process.exit(1);
            }
            if (argv.wait) {
                log("Invalidation Complete");
            } else {
                log("Invalidation Created");
            }
        });
    } else {
        module.exports = invalidate;
    }
    
    
    
    
    
}());
exports.handler = function (event, context) {

    console.log('Got event: ' + JSON.stringify(event, true, '  '));

    var bucketName = event.Records[0].s3.bucket.name;
    console.log('S3 Bucket affected: ' + bucketName);

    var theFile = event.Records[0].s3.object.key;
    console.log('Object changed: ' + theFile);

    // Trigger the invalidation just when the index file is changed
    if (theFile.indexOf('index') > -1) {

        // Creates the invalidation for the distribution that uses the bucket as a origin.
        function createInvalidation(params, deferred) {
            cloudfront.createInvalidation(params, function (error, data) {
                if (error) {
                    console.log('Got error creating the invalidation: ' + JSON.stringify(error, true, '  '));
                    deferred.reject();
                    return;
                }
                console.log('Success: ' + JSON.stringify(data.InvalidationBatch, true, '  '));
                deferred.resolve();
            });
        }

        // Returns the parameter with the item affected for the invalidation
        function buildInvalidationParameter(distribution) {
            return {
                DistributionId: distribution.Id,
                InvalidationBatch: {
                    CallerReference: '' + new Date().getTime(),
                    Paths: {
                        Quantity: 1,
                        Items: ['/*']
                    }
                }
            };
        }

        //Required policy, see README
        cloudfront.listDistributions({}, function (error, data) {
            var promises = [];
            if (error) {
                console.log('Error listing the CloudFront Distribution: ' + JSON.stringify(error, true, '  '));
                context.done('error', error);
                return;
            }

            data.Items.map(function (distribution) {
                var deferred = Q.defer();
                var exists = false;

                distribution.Origins.Items.map(function (origin) {
                    if (exists) {
                        return;
                    }

                    if (0 === origin.DomainName.indexOf(bucketName)) {
                        exists = true;
                        var name = distribution.DomainName;
                        if (distribution.Aliases.Quantity > 0) {
                            name = distribution.Aliases.Items[0];
                        }
                        console.log('Distribution: ' + distribution.Id + ' (' + name + ')');

                        // Parameters for a invalidation
                        var param = buildInvalidationParameter(distribution);
                        console.log('Parameter : ' + JSON.stringify(param, true, '  '));

                        // Creates the Invalidation
                        createInvalidation(param, deferred);
                    }
                });
                if (!exists) {
                    deferred.resolve();
                }
                promises.push(deferred.promise);
            });
            //Executes the promises
            Q.all(promises).then(function () {
                context.done(null, '');
            });
        });
    } else {
        console.log('The invalidation is triggered for the "index*" files, not for the file: ' + theFile);
    }
};
    staging: 'E3AUR9ALDYI683',
    production: 'EB2ZQZBEFJADJ',
  }

  const params = {
    DistributionId: stageMap[stage],
    InvalidationBatch: {
      Paths: {
        Quantity: paths.length,
        Items: paths,
      },
      CallerReference: (new Date().toISOString()),
    },
  }

  const cloudfront = new AWS.CloudFront()
  cloudfront.createInvalidation(params, function (err, data) {
    if (err) {
      logError(err)
      console.log(err.stack)
    } else {
      logInfo(`Invalidation id: ${data.Invalidation.Id}`)

      const waitForInvalidation = function () {
        cloudfront.getInvalidation({DistributionId: stageMap[stage], Id: data.Invalidation.Id}, function (err, data) {
          if (err) {
            logError(err)
            console.log(err.stack)
          } else {
            if (data.Invalidation.Status === 'InProgress') {
              process.stdout.write('.')
Example #27
0
module.exports = function(options) {

    options = options || {};
    var cloudfront = new AWS.CloudFront({
        accessKeyId: options.key,
        secretAccessKey: options.secret
    });

		// items = array of files to invalidate eg. [index.html, cache.appcache]
    var invalidateCache = function(items) {
			cloudfront.createInvalidation({
	      DistributionId: options.distributionId,
	      InvalidationBatch: {
	      	CallerReference: Date.now().toString(),
		      Paths: {
		        Quantity: items.length,
		        Items: items
		      }
		    }
	    }, function(err, data) {
	      if(err) {
	        gutil.log("Invalidation failed: ", err);
	      }
	      else {
	        gutil.log("Invalidation request successful - takes a few minutes to complete.");
	      }
			});
		};
		if(options.invalidateItems)
			invalidateCache(options.invalidateItems);
		
    var updateDefaultRootObject = function (defaultRootObject) {
        var deferred = Q.defer();

        // Get the existing distribution id
        cloudfront.getDistribution({ Id: options.distributionId }, function(err, data) {

            if (err) {                
                deferred.reject(err);
            } else {

                // AWS Service returns errors if we don't fix these
                if (data.DistributionConfig.Comment == null) data.DistributionConfig.Comment = '';
                if (data.DistributionConfig.Logging.Enabled == false) {
                    data.DistributionConfig.Logging.Bucket = '';
                    data.DistributionConfig.Logging.Prefix = '';
                }
                if (data.DistributionConfig.Origins.Items[0]) {
                	data.DistributionConfig.Origins.Items[0].S3OriginConfig.OriginAccessIdentity = '';
                }

                // Update the distribution with the new default root object
                data.DistributionConfig.DefaultRootObject = defaultRootObject;
                cloudfront.updateDistribution({
                    IfMatch: data.ETag,
                    Id: options.distributionId,
                    DistributionConfig: data.DistributionConfig
                }, function(err, data) {

                    if (err) {                
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }

                });

            }
        });   

        return deferred.promise;

    };

    return through.obj(function (file, enc, callback) {

        var self = this;

        // Update the default root object once we've found the index.html file
        if (file.path.match(/index\-[a-f0-9]{0,8}\.html(\.gz)?$/gi)) {           
        		// get rid of .gz (removed with gzip module) 
						file.path = file.path.replace(/\.gz$/gi, '')
            updateDefaultRootObject(path.basename(file.path))
                .then(function() {
                    return callback(null, file);                
                }, function(err) {
                    gutil.log(new gutil.PluginError('gulp-cloudfront', err));
                    callback(null, file);

                })

        } else {
            return callback(null, file);
        }

    });

};
Example #28
0
  grunt.registerMultiTask("cloudfront", DESC, function() {

    //get options
    var opts = this.options(DEFAULTS);

    if(_.isEmpty(opts.distributionId))
      return grunt.log.ok("No DistributionId specified");

    //mark as async
    var done = this.async();

    //whitelist allowed keys
    AWS.config.update(_.pick(opts,
      'accessKeyId',
      'secretAccessKey'
    ), true);
 
    //cloudfront client
    var cloudfront = new AWS.CloudFront();

    var subtasks = [];
    subtasks.push(createInvalidations);
    subtasks.push(createUpdates);
    async.series(subtasks, done);

    //------------------------------------------------

    //create records defined in opts.invalidations
    function createInvalidations(callback) {
      if(!opts.invalidations || !opts.invalidations.length)
        return callback();

      var params = {
        DistributionId: opts.distributionId,
        InvalidationBatch: {
          CallerReference: Date.now().toString(),
          Paths: {
            Quantity: opts.invalidations.length,
            Items: opts.invalidations
          }
        }
      };
      cloudfront.createInvalidation(params, function(err, data) {
        if (err) console.log(err, err.stack);
        else console.log(data);
        callback(err);
      });
    }

    function createUpdates(callback) {
      if(!opts.customErrorResponses && !opts.originPath && !opts.defaultRootObject)
        return callback();

      cloudfront.getDistribution({ Id: opts.distributionId }, function(err, res) {
        if (err) {
          console.log(err, err.stack);
          return callback(err);
        }

        var params = {
          Id: opts.distributionId,
          DistributionConfig: res.Distribution.DistributionConfig,
          IfMatch: res.ETag
        };

        if(opts.customErrorResponses){
          params.DistributionConfig.CustomErrorResponses = {
            Quantity: opts.customErrorResponses.length,
            Items: opts.customErrorResponses
          };
        }

        if(opts.originPath){
          params.DistributionConfig.Origins.Items[ 0 ].OriginPath = opts.originPath;
        }

        if(opts.defaultRootObject){
          params.DistributionConfig.DefaultRootObject = opts.defaultRootObject;
        }

        cloudfront.updateDistribution(params, function(err, data) {
          if (err) console.log(err, err.stack);
          else console.log(data);
          callback(err);
        });
      });

    }

  });
Example #29
0
var AWS = require('aws-sdk');
var randomstring = require('randomstring');

AWS.config.loadFromPath('credentials.json');

var reference = randomstring.generate(16); 
var cloudfront = new AWS.CloudFront();
var params = {
  DistributionId: 'YOUR_DISRTRIBUTION_ID', /* required */
  InvalidationBatch: { /* required */
    CallerReference: reference, /* required */
    Paths: { /* required */
      Quantity: 1, /* required */
      Items: [
        '/',
        /* more items */
      ]
    }
  }
};
cloudfront.createInvalidation(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});
module.exports = function (options) {
  options.wait = (options.wait === undefined || !options.wait) ? false : true;

  var cloudfront = new aws.CloudFront();

  cloudfront.config.update({
    accessKeyId: options.accessKeyId || process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: options.secretAccessKey || process.env.AWS_SECRET_ACCESS_KEY,
    sessionToken: options.sessionToken || process.env.AWS_SESSION_TOKEN
  });

  var files = [];

  var complain = function (err, msg, callback) {
    throw new util.PluginError('gulp-cloudfront-invalidate', msg + ': ' + err);
    return callback(false);
  };

  var check = function (id, callback) {
    cloudfront.getInvalidation({
      DistributionId: options.distribution,
      Id: id
    }, function (err, res) {
      if (err) return complain(err, 'Could not check on invalidation', callback);

      if (res.Invalidation.Status === 'Completed') {
        return callback();
      } else {
        setTimeout(function () {
          check(id, callback);
        }, 1000);
      }
    })
  };

  var processFile = function (file, encoding, callback) {
    // https://github.com/pgherveou/gulp-awspublish/blob/master/lib/log-reporter.js
    var state;

    if (!file.s3) return callback(null, file);
    if (!file.s3.state) return callback(null, file);
    if (options.states &&
        options.states.indexOf(file.s3.state) === -1) return callback(null, file);

    switch (file.s3.state) {
      case 'update':
      case 'create':
      case 'delete':
        files.push(file.s3.path);
        break;
      case 'cache':
      case 'skip':
        break;
      default:
        util.log('Unknown state: ' + file.s3.state);
        break;
    }

    return callback();
  };

  var invalidate = function(callback){
    if(files.length == 0) return callback();

    files = files.map(function(file) {
      return '/' + file;
    });

    cloudfront.createInvalidation({
      DistributionId: options.distribution,
      InvalidationBatch: {
        CallerReference: Date.now().toString(),
        Paths: {
          Quantity: files.length,
          Items: files
        }
      }
    }, function (err, res) {
      if (err) return complain(err, 'Could not invalidate cloudfront', callback);

      util.log('Cloudfront invalidation created: ' + res.Invalidation.Id);

      if (!options.wait) {
        return callback();
      }

      check(res.Invalidation.Id, callback);
    });
  }

  return through.obj(processFile, invalidate);
};