如何在 Jenkins 中 运行 docker rmi $(docker images -a -q) 作为 ssh 脚本的一部分

How to run docker rmi $(docker images -a -q) in Jenkins as part of ssh script

我正在构建 Jenkins 作业以在 AWS EC2 实例上构建 docker 容器,这是给出错误的 Jenkins 脚本示例:

#!/bin/bash -e
# Not giving the IP here but I guess you can understand
HOST = Some IP address of EC2 instance in AWS 

# Current Project workspace 
# Download source code and create a tar and then SCP it in to AWS EC2
# So my Code is copied in to AWS EC2 instance now ...
# Now do the SSH and run the script on AWS EC2 instance
ssh -o StrictHostKeyChecking=no -i MySecrets.pem ec2-user@$HOST \
    "tar xvf pc.tar && \
    cd my_project_source_code && \
    docker stop $(docker ps -a -q) && \
    docker rmi $(docker images -a -q) && \
    sh -c 'nohup docker-compose kill  > /dev/null 2>&1 &' && \
    docker-compose build --no-cache && \
    sh -c 'nohup docker-compose up > /dev/null 2>&1 &' "

当我在 Jenkins 中构建此作业时,它失败并在输出控制台上显示以下错误:

"docker stop" requires at least 1 argument(s). See 'docker stop --help'.

Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...]

Stop one or more running containers Build step 'Execute shell' marked build as failure

所以我的问题是我的 bash 脚本有什么问题?

单独说明:

我能够 运行 docker 停止 $(docker ps -a -q) 当我在 CLI 上通过 ssh 进入 EC2。但是当 Jenkins 作业 bash shell 脚本中的相同命令 运行 时,它不会将其识别为有效脚本。我在这里做错了什么?这似乎是我对如何在 Jenkins Job 的 bash shell 脚本中 运行 这个命令的一些误解,但我不完全确定。

如果您希望在脚本中替换远程端的 运行,则需要在本地 shell 不会尝试的上下文中将其传递给 ssh先评价一下。双引号不是那个上下文。

引用的 heredoc 符合要求:

ssh -o StrictHostKeyChecking=no -i MySecrets.pem "ec2-user@$HOST" 'bash -s' <<'EOF'
 tar xvf pc.tar                                        || exit
 cd my_project_source_code                             || exit
 docker stop $(docker ps -a -q)                        || exit
 docker rmi $(docker images -a -q)                     || exit
 sh -c 'nohup docker-compose kill  > /dev/null 2>&1 &' || exit
 docker-compose build --no-cache                       || exit
 sh -c 'nohup docker-compose up > /dev/null 2>&1 &'    || exit
EOF