Jenkins 构建前端服务更新控制

在当今的快节奏开发环境中,确保前端服务的高效和可靠更新至关重要。本文将介绍如何通过AWS服务(如ECS和S3)以及Jenkins进行参数化构建,实现前端服务的自动化部署和更新控制。我们将深入了解使用Python脚本管理部署流程,以及如何在Jenkins中配置参数化构建,使得服务的部署更加灵活和可配置。

部署脚本

Python脚本管理部署流程

首先,让我们来看一下负责编排部署流程的Python脚本。该脚本使用Boto3库与AWS服务进行交互,并利用Requests库发起HTTP请求。以下是关键功能的概述:

#!/usr/bin/python3
import os
import requests
import boto3
import json


def get_secret(secret_name, region_name):
    """
    Retrieves the specified secret from AWS Secrets Manager.

    Args:
        secret_name (str): The name of the secret.
        region_name (str): The AWS region where the secret is stored.

    Returns:
        dict: The decoded JSON representation of the secret.
    """
    session = boto3.session.Session()
    client = session.client(service_name='secretsmanager', region_name=region_name)
    get_secret_value_response = client.get_secret_value(SecretId=secret_name)
    return json.loads(get_secret_value_response['SecretString'])


def send_dingding(service_name, token):
    """
    Sends a message to DingTalk notifying the successful restart of a service.

    Args:
        service_name (str): Name of the service being restarted.
        token (str): DingTalk access token.
    """
    headers = {'Content-Type': 'application/json'}
    message = f"<font face='黑体' color='#00EC00'>Restart {service_name} Success</font>\n"
    data = {"msgtype": "markdown", "markdown": {"title": f"Restart {service_name} Success", "text": message}}
    response = requests.post(f"https://oapi.dingtalk.com/robot/send?access_token={token}", headers=headers, json=data)
    print(response.text)


def update_ecs_service(service_name, cluster_name='frontend-pro'):
    """
    Updates the ECS service with a new deployment.

    Args:
        service_name (str): Name of the ECS service.
        cluster_name (str): Name of the ECS cluster.
    """
    boto3.client('ecs').update_service(cluster=cluster_name, service=service_name, taskDefinition=service_name,
                                       forceNewDeployment=True)
    print("****************************更新容器************************************")


def upload_to_s3(service_name):
    """
    Uploads code to S3 bucket.

    Args:
        service_name (str): Name of the service.
    """
    s3_client = boto3.client('s3')
    print("****************************上传代码************************************")
    s3_client.sync(f"s3://deploy-github-fe/{service_name}/", f"s3://govee-static/prod/{service_name}/",
                   acl='public-read')


def clear_url_cache():
    """
    Clears the URL cache by sending an HTTP POST request.
    """
    response = requests.post("https://apph5-api.my.com/h5/v1/commom/cache/reset")
    print(response.text)


def deploy_services(service_names):
    """
    Deploys services based on their names.

    Args:
        service_names (list): List of service names to be deployed.
    """
    for service_name in service_names:
        if service_name == "pro-trade-fe":
            upload_to_s3(service_name)
            update_ecs_service(service_name)
            send_dingding(service_name, os.environ['DINGDING_TOKEN'])
        elif service_name in ["pro-auth-fe", "prod-h5-game-fe"]:
            upload_to_s3(service_name)
            clear_url_cache()
            send_dingding(service_name, os.environ['DINGDING_TOKEN'])
        elif service_name == "prod-life-web-fe":
            update_ecs_service(service_name)
            send_dingding(service_name, os.environ['DINGDING_TOKEN'])
        elif service_name in ["prod-app-h5-fe", "prod-app-hd-fe"]:
            upload_to_s3(service_name)
            update_ecs_service(service_name)
            clear_url_cache()
            send_dingding(service_name, os.environ['DINGDING_TOKEN'])
        elif service_name == "prod-minger-os-web-fe":
            update_ecs_service(service_name)
            send_dingding(service_name, os.environ['DINGDING_TOKEN'])
        else:
            upload_to_s3(service_name)
            update_ecs_service(service_name)
            clear_url_cache()
            send_dingding(service_name, os.environ['DINGDING_TOKEN'])


if __name__ == "__main__":
    # Get DingDing token from AWS Secrets Manager
    secrets = get_secret('base', 'us-east-1')
    token = secrets.get('BUILD1_TOKEN', '')  # Retrieve the token, default to empty string if not found

    # Get service names from environment variable
    service_names = os.environ['SERVICE_NAMES'].split(',')

    # Execute deployment
    deploy_services(service_names)

关键功能解析

  • ​get_secret​:从AWS Secrets Manager检索指定的秘密。
  • ​send_dingding​:向DingTalk发送有关服务重新启动的消息。
  • ​update_ecs_service​:使用新的部署更新ECS服务。
  • ​upload_to_s3​:将代码上传到S3桶。
  • ​clear_url_cache​:通过发送HTTP POST请求清除URL缓存。
  • ​deploy_services​:部署服务的主要函数。

Shell脚本管理部署流程

#!/bin/bash

# Function to get secret from AWS Secrets Manager
get_secret() {
  secret_name=$1
  region_name=$2
  aws secretsmanager get-secret-value --secret-id $secret_name --region $region_name --query 'SecretString' --output text
}

# Function to send DingTalk message
send_dingding() {
  service_name=$1
  token=$2
  message="<font face='黑体' color='#00EC00'>Restart $service_name Success</font>"
  curl -s -X POST "https://oapi.dingtalk.com/robot/send?access_token=$token" -H "Content-Type: application/json" \
    -d "{\"msgtype\": \"markdown\", \"markdown\": {\"title\": \"Restart $service_name Success\", \"text\": \"$message\"}}"
}

# Function to update ECS service
update_ecs_service() {
  service_name=$1
  cluster_name='frontend-pro'
  aws ecs update-service --cluster $cluster_name --service $service_name --task-definition $service_name --force-new-deployment
  echo "****************************更新容器************************************"
}

# Function to upload to S3
upload_to_s3() {
  service_name=$1
  aws s3 sync "s3://deploy-github-fe/$service_name/" "s3://govee-static/prod/$service_name/" --acl public-read
  echo "****************************上传代码************************************"
}

# Function to clear URL cache
clear_url_cache() {
  curl -s -X POST "https://apph5-api.my.com/h5/v1/commom/cache/reset"
  echo "****************************清理URL缓存************************************"
}

# Function to deploy services
deploy_services() {
  service_names=$@
  for service_name in $service_names; do
    case $service_name in
      "pro-trade-fe")
        upload_to_s3 $service_name
        update_ecs_service $service_name
        send_dingding $service_name $DINGDING_TOKEN
        ;;
      "pro-auth-fe"|"prod-h5-game-fe")
        upload_to_s3 $service_name
        clear_url_cache
        send_dingding $service_name $DINGDING_TOKEN
        ;;
      "prod-life-web-fe")
        update_ecs_service $service_name
        send_dingding $service_name $DINGDING_TOKEN
        ;;
      "prod-app-h5-fe"|"prod-app-hd-fe")
        upload_to_s3 $service_name
        update_ecs_service $service_name
        clear_url_cache
        send_dingding $service_name $DINGDING_TOKEN
        ;;
      "prod-minger-os-web-fe")
        update_ecs_service $service_name
        send_dingding $service_name $DINGDING_TOKEN
        ;;
      *)
        upload_to_s3 $service_name
        update_ecs_service $service_name
        clear_url_cache
        send_dingding $service_name $DINGDING_TOKEN
        ;;
    esac
  done
}

# Main execution
secrets=$(get_secret 'base' 'us-east-1')
export DINGDING_TOKEN=$(echo $secrets | jq -r .BUILD1_TOKEN)

# Get service names from environment variable
service_names=${SERVICE_NAMES//,/ }

# Execute deployment
deploy_services $service_names

Jenkins中的参数化构建

为了使部署流程更加灵活和可配置,我们将该脚本集成到Jenkins中,并使用Extended Choice Parameter插件进行参数化构建。这使用户能够在Jenkins构建期间选择要部署的服务。

Jenkins配置

  • Extended Choice Parameter:
  • Name: SERVICE_NAMES
  • Parameter Type: Check Boxes
  • Number of Visible Items: 10
  • Delimiter:,
  • Quote Value: prod-app-hd-fe, prod-app-h5-fe, prod-govee-life-web-fe, prod-community-web-fe, prod-app-platform-fe, pro-trade-fe, pro-auth-fe, prod-h5-game-fe, pro-app-h5-fe, prod-promotion-app-h5-fe, prod-desktop-web-fe, prod-app-mall-fe, prod-minger-os-web-fe

结论

通过自动化部署流水线,我们不仅节省了时间,还减少了人为错误的风险。通过Python脚本和Jenkins的集成,只需几次点击即可轻松部署前端服务到AWS。根据您的特定用例进行定制,享受简化的部署流程。

在您的博文中,您可以进一步优化、整理和详细说明脚本的生产控制、开发最佳实践等方面的内容,以使读者更好地理解和应用这一自动化流程。祝愉快编写博文!

相关推荐
一休哥助手15 分钟前
全面解析 Linux 系统监控与性能优化
linux·运维·性能优化
m0_7482561415 分钟前
前端 MYTED单篇TED词汇学习功能优化
前端·学习
watl033 分钟前
【Android】unzip aar删除冲突classes再zip
android·linux·运维
团儿.1 小时前
Docker服务发现新纪元:探索Consul的无限魅力
运维·docker·云计算·服务发现·consul
赵大仁1 小时前
在 CentOS 7 上安装 Node.js 20 并升级 GCC、make 和 glibc
linux·运维·服务器·ide·ubuntu·centos·计算机基础
vvw&1 小时前
Docker Build 命令详解:在 Ubuntu 上构建 Docker 镜像教程
linux·运维·服务器·ubuntu·docker·容器·开源
李白你好1 小时前
家用无线路由器的 2.4GHz 和 5GHz
运维·网络
小白学前端6661 小时前
React Router 深入指南:从入门到进阶
前端·react.js·react
苹果醋31 小时前
React系列(八)——React进阶知识点拓展
运维·vue.js·spring boot·nginx·课程设计
冷冰鱼2 小时前
【问题实录】服务器ping不通win11笔记本
运维·服务器