Docker运行的GitHub Action中,如何在PS1脚本调用GitHub Input环境变量?
解决Docker运行的GitHub Action中PowerShell脚本读取输入变量的问题
我创建了一个带URL和路径输入项的GitHub Action,通过Docker运行PowerShell脚本。现在想在entrypoint.ps1里调用GitHub Input设置的环境变量,但试了多种方法都没成功,该怎么实现?
现有配置
GitHub Action 配置
inputs: url: # id of input description: 'URL to download file from' required: true path: description: 'Path to store output file' required: false default: '/' runs: using: 'docker' image: 'Dockerfile' args: - ${{ inputs.url }} - ${{ inputs.path }}
Dockerfile
FROM ubuntu:18.04 LABEL "com.github.actions.name"="Download File Action" LABEL "com.github.actions.description"="GitHub Action to download files from certain URL" RUN apt-get update \ && apt-get install wget -y \ && wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb \ && dpkg -i packages-microsoft-prod.deb \ && apt-get update \ && apt-get install -y powershell ADD entrypoint.ps1 /entrypoint.ps1 ENTRYPOINT ["pwsh", "/entrypoint.ps1"]
待修改的PowerShell脚本
Invoke-WebRequest -Uri '$env:INPUT_URL' -OutFile '$env:GITHUB_WORKSPACE\$env:INPUT_PATH'
解决方案
方法一:通过环境变量读取输入
GitHub Action不会自动将inputs注入为Docker容器内的环境变量,需要手动配置映射:
- 修改GitHub Action配置,在
runs下添加env字段,将输入项转为环境变量:
inputs: url: description: 'URL to download file from' required: true path: description: 'Path to store output file' required: false default: '/' runs: using: 'docker' image: 'Dockerfile' env: INPUT_URL: ${{ inputs.url }} INPUT_PATH: ${{ inputs.path }} args: - ${{ inputs.url }} - ${{ inputs.path }}
- 调整PowerShell脚本:必须用双引号包裹字符串(单引号不会解析环境变量),同时注意Linux环境路径分隔符为
/而非\:
Invoke-WebRequest -Uri "$env:INPUT_URL" -OutFile "$env:GITHUB_WORKSPACE/$env:INPUT_PATH"
方法二:直接读取脚本传入的参数
当前Action配置已经将inputs作为命令行参数传递给了PowerShell脚本,可直接读取参数:
修改PowerShell脚本,通过param定义参数(推荐,可读性更强):
param( [string]$Url, [string]$Path = '/' ) Invoke-WebRequest -Uri $Url -OutFile "$env:GITHUB_WORKSPACE/$Path"
或者直接使用$args数组:
$url = $args[0] $path = if ($args[1]) { $args[1] } else { '/' } Invoke-WebRequest -Uri $url -OutFile "$env:GITHUB_WORKSPACE/$path"
这种方法无需修改Action配置,直接利用已传递的参数即可。
内容的提问来源于stack exchange,提问作者Minionguyjpro
相关产品推荐
相关产品推荐

