My GitHub @otobrglez

Using Grunt for S3 deployment / sync

20 Apr 2015 / front-end

For my recent AngularJS project SNAGR I've decided that I'm gonna automate deployment process as much as possible.

Because, who has the time to do everything manually this days - right? :)

Project setup

Hello Amazon Simple Storage and s3cmd

After grunt build produces ./dist folder I use s3cmd to sync new content with my S3 bucket.

s3cmd sync -c s3.conf -r ./dist/* s3://<my bucket>

s3.conf is configuration file that holds all credentials information. You can configure your own with following command:

s3cmd --configure -c s3.conf

Sync command has couple of options. With -P your MIME types will be preserved with --delete-removed files that are no longer present locally will be removed from your S3 bucket. Check documentation about more flags.

Now GRUNT it!

Manually running s3cmd sync after build is just boring. So lets add it to GRUNT "workflow" with two tasks. First task that actually syncs ./dist folder

grunt.registerTask('deployToS3', 'Deploying to S3 bucket', function(target){
  var done = this.async();
  var command = "/usr/local/bin/s3cmd";

  var child = grunt.util.spawn({
    grunt: false,
    cmd: command,
    args: 'sync -c s3.conf -r ./dist/* -P s3://<my bucket>'.split(" "),
    opts: {
      stdio: 'inherit'
    }
  }, function(error, result, code){
    if(code != 0 && error !== null) grunt.fatal("Error sycing with S3 bucket");

    grunt.log.writeln(String(result).trim());

    done();
  });
});

Second task that first builds project and then invokes syncing.

grunt.registerTask('deploy', [
  'build',
  'deployToS3'
]);

Now, all you have to do is...

grunt deploy

... and share this. ;)

Cheers!


comments powered by Disqus