HUGO

Use AWS_PROFILE environment variable when using hugo deploy with S3

If you are deploying to AWS S3 / Cloudfront, you can take advantage of hugo deploy to do it. Make sure you configure your aws cli command, putting your specific IAM credentials in a named profile, in ~/.aws/credentials such as:

[deploy-coolsite]
aws_access_key_id = ABCDEFGHIJK123456
aws_secret_access_key = fjdkjfieuciufu7s6fshkjw9d8d798ssfa

I use a zsh function to deploy and you could do something similar in a CI workflow as well.

function hugodeploy-coolsite (){
    echo "====== Deploy coolsite.jp site to AWS S3 ======"
    _hugobin="$HOME/gocode/bin/hugo"
    _awsbin="/usr/local/bin/aws"
    _workingdir="$HOME/dev/coolsite.jp"
    _current_aws_profile="$AWS_PROFILE"
    cd ${_workingdir}
    export AWS_PROFILE="deploy-coolsite"
    echo "🤖 Confirm aws profile via \"aws configure list\""
    ${_awsbin} configure list
    echo "🤖 Build and deploy site"
    ${_hugobin} && ${_hugobin} deploy --invalidateCDN --target coolsitejp --verbose
    [[ -z "$_current_aws_profile" ]] && unset AWS_PROFILE || export AWS_PROFILE=${_current_aws_profile}
}

This function sets some local vars, sets AWS_PROFILE via export then confirms it is set, then builds and deploys the site via hugo and hugo deploy. The site has a config file with the “coolsitejp” target set for hugo deploy, and under that is specified which AWS S3 bucket to deploy to. Use export instead of a simple assignation like I am doing with _hugobin etc, because you want to have the variable ready for use when the script invokes hugo to build and deploy the site. The last line unsets AWS_PROFILE for good measure if it was not set already, or resets it to whatever it was set to initially.

@shashank mentioned in another thread that such a function would be for an individual. Indeed that’s true. It’s far better to use a CI/CD workflow linked to your git repo if you’re working in a group. But for a personal site or testing, the above works well.

But note, setting AWS_PROFILE is not the way to go for a situation where you’re installing or building on the fly, as in a CI/CD workflow. Rather, you’d need to just set the two variables AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY however you can. Don’t commit them to git or put them in say a local cleartext file. Instead, use the “secrets” facility of your CI/CD provider to set them as variables, then refer to those in the script, setting them as needed. If those are set, hugo deploy will use them.

3 Likes