|
| 1 | +name: Deploy to EC2 |
| 2 | + |
| 3 | +on: |
| 4 | + push: |
| 5 | + branches: |
| 6 | + - devops/a3 |
| 7 | + tags: |
| 8 | + - 'deploy-*' # Matches tags like deploy-dev, deploy-qa, deploy-prod |
| 9 | + workflow_dispatch: |
| 10 | + inputs: |
| 11 | + stage: |
| 12 | + description: 'Deployment stage (dev, qa, prod)' |
| 13 | + required: true |
| 14 | + default: 'dev' |
| 15 | + type: choice |
| 16 | + options: |
| 17 | + - dev |
| 18 | + - qa |
| 19 | + - prod |
| 20 | + |
| 21 | +env: |
| 22 | + AWS_REGION: ap-south-1 |
| 23 | + |
| 24 | +jobs: |
| 25 | + deploy: |
| 26 | + runs-on: ubuntu-latest |
| 27 | + |
| 28 | + steps: |
| 29 | + - name: Determine Stage |
| 30 | + id: set_stage |
| 31 | + run: | |
| 32 | + STAGE_INPUT="${{ github.event.inputs.stage }}" |
| 33 | + STAGE="" |
| 34 | +
|
| 35 | + if [[ "${GITHUB_REF}" == refs/tags/deploy-* ]]; then |
| 36 | + STAGE="${GITHUB_REF#refs/tags/deploy-}" |
| 37 | + echo "Tag trigger detected. Stage set to: $STAGE" |
| 38 | + elif [[ -n "$STAGE_INPUT" ]]; then |
| 39 | + STAGE="$STAGE_INPUT" |
| 40 | + echo "Manual trigger detected. Stage set to: $STAGE" |
| 41 | + else |
| 42 | + echo "Branch trigger detected (main). Defaulting stage to dev." |
| 43 | + STAGE="dev" |
| 44 | + fi |
| 45 | +
|
| 46 | + # Validate stage |
| 47 | + if [[ "$STAGE" != "dev" && "$STAGE" != "qa" && "$STAGE" != "prod" ]]; then |
| 48 | + echo "Invalid stage: $STAGE. Must be dev, qa, or prod." |
| 49 | + exit 1 |
| 50 | + fi |
| 51 | +
|
| 52 | + echo "STAGE=$STAGE" >> $GITHUB_ENV |
| 53 | +
|
| 54 | + # Checkout Code |
| 55 | + - name: Checkout repository |
| 56 | + uses: actions/checkout@v4 |
| 57 | + |
| 58 | + # Configure AWS Credentials |
| 59 | + - name: Configure AWS Credentials |
| 60 | + uses: aws-actions/configure-aws-credentials@v4 |
| 61 | + with: |
| 62 | + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} |
| 63 | + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} |
| 64 | + aws-region: ${{ env.AWS_REGION }} |
| 65 | + |
| 66 | + # Install Dependencies |
| 67 | + - name: Install dependencies |
| 68 | + run: | |
| 69 | + sudo apt update |
| 70 | + sudo apt install -y unzip curl terraform |
| 71 | +
|
| 72 | + # Setup SSH Private Key |
| 73 | + - name: Setup SSH Private Key |
| 74 | + run: | |
| 75 | + echo "${{ secrets.SSH_PRIVATE_KEY }}" > ec2_key.pem |
| 76 | + chmod 400 ec2_key.pem |
| 77 | +
|
| 78 | + # Make deploy.sh executable |
| 79 | + - name: Make deploy.sh executable |
| 80 | + run: chmod +x scripts/deploy.sh |
| 81 | + |
| 82 | + # Run deploy.sh with detected stage |
| 83 | + - name: Run deploy.sh |
| 84 | + run: | |
| 85 | + export PRIVATE_KEY_PATH="./ec2_key.pem" |
| 86 | + ./scripts/deploy.sh $STAGE |
0 commit comments