#!/bin/bash
#-----------------
#app_name:yangxv
#app_time:2024/12/27
#app_home:0.12/data/www/devops/scripts/kubectl_create.sh
#----------------

namespace_name=$1    # 命名空间
deployment_name=$2    # 部署名称
image_name=$3   # 镜像名称
echo $3
docker_name=$(grep dockerfile: .drone.yml | awk '{print $2}' | head -n 1)   # 查找Dockerfile名称
docker_port=$(grep EXPOSE $docker_name | awk '{print $2}')   # 查找Dockerfile端口

#判断是否存在指定的工作负载，若不存在则创建并配置:更改容器名称、开放服务
kubectl get deployment $deployment_name -n $namespace_name --no-headers --output=name || (kubectl create deployment $deployment_name \
--image="$image_name" \
-n $namespace_name \
--replicas=1 \
--port=$docker_port \
--dry-run=client -o yaml | kubectl apply -f - \
&& kubectl patch deployment $deployment_name -n $namespace_name --type=json -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/name", "value": "'$deployment_name'"}]' \
&& kubectl expose deployment $deployment_name --name=$deployment_name --type=ClusterIP --port=$docker_port --target-port=$docker_port -n $namespace_name )
