从gitlab-ci.yml启动/停止远程服务器上的tomcat

时间:2019-07-14 08:59:31

标签: java spring-boot gitlab gitlab-ci

我正在尝试编写一个脚本,以使用 gitlab-ci.yml 文件从gitlab部署Spring Boot应用程序。以下是文件的内容。

image: maven:3-jdk-8

services:
    - docker:dind

stages:
    - build
    - deploy

build:
    stage: build
    script: 
        - echo "Packaging"
        - mvn clean package -DskipTests
    artifacts:
        expire_in: 1 week
        when: always
        paths:
            - target/app.war

deploy:
    stage: deploy
    dependencies:
        - build
    script:
        - "#!/bin/sh"
        - chmod og= $PRODUCTION_SERVER_PASSWORD
        - scp -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no target/app.war $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER:/home/ubuntu/wars
        - ssh -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER sh /opt/tomcat/bin/catalina.sh stop
        - ssh -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER rm -r /opt/tomcat/webapps/ROOT*
        - ssh -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER cp -r /home/ubuntu/wars/app.war /opt/tomcat/webapps/ROOT.war
        - ssh -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER sh /opt/tomcat/bin/catalina.sh start
    environment:
        name: production
        url: <server-url>
    when: manual

触发部署阶段时,该行出现错误

- ssh -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER sh /opt/tomcat/bin/catalina.sh stop

发生的错误是

Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
At least one of these environment variable is needed to run this program

但是当我添加

- echo $JAVA_HOME
script阶段的deploy下,

打印出/usr/local/openjdk-8。我还无法理解这一点。为什么说JAVA_HOME未定义。我是否必须明确定义JAVA_HOME,如果需要,在哪里以及如何进行定义?

1 个答案:

答案 0 :(得分:0)

请尝试以下操作:

script:
        - "#!/bin/sh"
        - chmod og= $PRODUCTION_SERVER_PASSWORD
        - scp -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no target/app.war $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER:/home/ubuntu/wars
        - ssh -i "$PRODUCTION_SERVER_PASSWORD" -o StrictHostKeyChecking=no $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER "
          sh /opt/tomcat/bin/catalina.sh stop
          rm -r /opt/tomcat/webapps/ROOT*
          cp -r /home/ubuntu/wars/app.war /opt/tomcat/webapps/ROOT.war
          export JAVA_HOME=/usr/local/openjdk-8
          /opt/tomcat/bin/catalina.sh start
          "
    environment:
        name: production

您不需要执行多个ssh,如果JAVA_HOME是正确的,则无需执行第二个ssh,则只需执行简单的export JAVA_HOME=/path/to/jdk/bin/就可以了。