【问题标题】:Command substitution error via SSH with Gitlab CI通过 SSH 与 Gitlab CI 的命令替换错误
【发布时间】:2020-02-15 14:23:51
【问题描述】:

我想使用 gitlab-ci 通过 SSH 执行 shell,但遇到错误。

变量有这些值:

DEV_SERVER=myserver.domain.com
CODE_APP=4A
CI_COMMIT_REF_SLUG=pretorien-feature-ci

gitlab-ci.yml 的一部分看起来像这样:

review_app:
    stage: review
    before_script:
        # SSH key configuration
        # ...
    script:
        - ssh dev@${DEV_SERVER} \
                "CONTAINER_PORT=$(docker port app_${CODE_APP}-${CI_COMMIT_REF_SLUG} 80 | cut -d ':' -f2)" \
                "&& echo 'My container port : ${CONTAINER_PORT}' > result.txt"

Gitlab CI 返回此错误/usr/bin/bash: line 109: docker: command not found

我尝试使用 docker 二进制路径 (/usr/bin/docker) 或 $(which docker) 更改 docker 命令,但我遇到了同样的问题。

所以,我决定使用不同的方法:

review_app:
    stage: review
    before_script:
        # SSH key configuration
        # ...
    script:
        - ssh dev@${DEV_SERVER} \            
            "{ read CONTAINER_PORT _; } < <(docker port app_${CODE_APP}-${CI_COMMIT_REF_SLUG} 80 | cut -d ':' -f2)" \
            "&& echo 'My container port : ${CONTAINER_PORT}' > result.txt"

但是,在这种情况下,文件 result.txt 是 empty 并且变量 CONTAINER_PORT 也是。

在这两种情况下,我都直接在 shell 中检查了命令,结果很好,我可以读取 result.txt 中的 CONTAINER_PORT 值

【问题讨论】:

    标签: shell ssh gitlab gitlab-ci


    【解决方案1】:

    你所做的使docker 命令在 gitlab CI 运行器中运行,它可能不知道它。我假设您想在 ${DEV_SERVER} 上运行docker 命令,因此您需要正确转义或将子命令括在撇号中,以确保它不会过早扩展。这样的事情应该这样做:

        - ssh dev@${DEV_SERVER} \
                "CONTAINER_PORT=\$(docker port app_${CODE_APP}-${CI_COMMIT_REF_SLUG} 80 | cut -d ':' -f2)" \
                "&& echo 'My container port : ${CONTAINER_PORT}' > result.txt"
    

    我的测试:

    $ ssh localhost "echo \$(echo \$SSH_CLIENT)"
    

    正确写入SSH连接信息,该信息仅在会话中可用,在本地会话中不可用。

    【讨论】:

      【解决方案2】:

      非常感谢!有用 :) 最后,我还使用了 printf 而不是 echo

      - ssh dev@${DEV_SERVER} \
                  "cd ${DEV_REVIEW_DIRECTORY}/${CODE_APP}-${CI_COMMIT_REF_SLUG}/" \
                  "&& CONTAINER_PORT=\$(docker port app_${CODE_APP}-${CI_COMMIT_REF_SLUG} 80 | cut -d ':' -f2)" \
                  "&& printf '<html><head><script type=\"text/javascript\">window.location.replace(\"http://%q:%q\");</script></head></html>' ${DEV_SERVER} \$CONTAINER_PORT > redirect.html"
      

      【讨论】:

        猜你喜欢
        • 2019-07-14
        • 1970-01-01
        • 2022-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        相关资源
        最近更新 更多