ShellScript で MFA 認証設定済の IAM を使用して S3 に画像をアップロードする方法について調査した結果を備忘録として残しておく

環境

  • OS: MacOS
  • aws-mfa をインストールして登録済
    • aws-mfa 設定を参照

aws-mfa 設定

  1. 通常の aws profile を設定
  2. 1 で設定した «profile 名»-long-term で Profile を設定
  3. 追加で ~/.aws/credentials に以下を設定
[<profile 名>-long-term]
aws_mfa_device = <<arn:aws:iam::*:mfa/${aws:username}>>

フォルダ構成

./
├── img/
│    └── image_001.png
└── upload_image.sh

実際のコード

«…» 部分は実際の環境に応じて書き換える

#!/bin/sh

# Shared
AWS_PROFILE_PREFIX=<<AWS Profile Prefix>>
IMAGE_UPLOAD_DIR=img

read -p "Which environment connect to? (dev/stg/prd): " input_environment

# Convert to uppercase
environment=$(echo "${input_environment}" | tr '[:lower:]' '[:upper:]')

echo "【Start Processing】$(date "+%Y/%m/%d %H:%M:%S")" >> ${LOG_FILE} 2>&1

# Check the environment
case "${input_environment}" in
  "dev" | "stg" | "prd")
    echo "Connecting to ${environment} environment..." >> ${LOG_FILE} 2>&1

    # AWS MFA Authentication
    aws-mfa --profile=${AWS_PROFILE_PREFIX}-${input_environment} >> ${LOG_FILE} 2>&1

    # Set environment variables
    AWS_PROFILE=$(eval "echo \${AWS_PROFILE_PREFIX}-${input_environment}")
    AWS_S3_IMAGE_UPLOAD_DIR=$(eval "echo s3-bucket-${input_environment}-to/path/");;
  *)
    echo "Please enter the correct environment." >> ${LOG_FILE} 2>&1
    echo "【End Processing】$(date "+%Y/%m/%d %H:%M:%S")" >> ${LOG_FILE} 2>&1
    exit;;
esac

echo "【Start Upload Image】$(date "+%Y/%m/%d %H:%M:%S")" >> ${LOG_FILE} 2>&1
# Remove .DS_Store
find . -name ".DS_Store" | xargs rm -f

# Upload images to S3
aws s3 cp ./${IMAGE_UPLOAD_DIR} s3://${AWS_S3_IMAGE_UPLOAD_DIR} --profile=${AWS_PROFILE} --recursive >> ${LOG_FILE} 2>&1
echo "【End Upload Image】$(date "+%Y/%m/%d %H:%M:%S")" >> ${LOG_FILE} 2>&1

echo "【End Processing】$(date "+%Y/%m/%d %H:%M:%S")" >> ${LOG_FILE} 2>&1