You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure CI访问私有Bitbucket仓库时npm install报错及路径问题求助

解决Azure CI中npm安装私有Bitbucket依赖的SSH权限问题

问题描述

我的package.json文件内有若干依赖来自私有Bitbucket仓库,使用Azure CI执行npm install操作时,出现git@bitbucket.org: Permission denied (publickey)权限拒绝错误。我已通过ssh-keygen生成SSH密钥,将id_rsa.pub添加至Bitbucket仓库的SSH keys中,并将私钥作为安全变量配置到Azure CI。但在Azure Pipeline脚本中尝试将私钥写入$(Agent.HomeDirectory)\.ssh\id_rsa时,提示The system cannot find the path specified错误。

我的Azure-pipeline.yaml配置如下:

trigger:
- mybranch

variables:
  sshkey: $(key)

jobs:
- job: Job_1
  pool:
    vmImage: windows-latest
  steps:


  - script: |
      echo "$(sshkey)" > "$(Agent.HomeDirectory)\.ssh\id_rsa"
      echo "Host bitbucket.org" > "$(Agent.HomeDirectory)\.ssh\config"
      echo "  StrictHostKeyChecking no" >> "$(Agent.HomeDirectory)\.ssh\config"

  - script: choco install git -y

  - script: npm install

解决方法

问题出在Windows代理机器默认不存在.ssh目录,直接写入文件会报错,同时还需要处理私钥的权限问题(SSH对私钥权限有严格要求)。修改后的Pipeline配置如下:

trigger:
- mybranch

variables:
  sshkey: $(key)

jobs:
- job: Job_1
  pool:
    vmImage: windows-latest
  steps:
  - script: |
      # 先创建.ssh目录,-Force参数确保目录不存在时自动创建
      mkdir "$(Agent.HomeDirectory)\.ssh" -Force
      # 使用Out-File写入私钥,避免echo的编码问题
      "$(sshkey)" | Out-File -FilePath "$(Agent.HomeDirectory)\.ssh\id_rsa" -Encoding ASCII
      # 写入SSH配置文件
      "Host bitbucket.org" | Out-File -FilePath "$(Agent.HomeDirectory)\.ssh\config" -Encoding ASCII
      "  StrictHostKeyChecking no" | Out-File -FilePath "$(Agent.HomeDirectory)\.ssh\config" -Encoding ASCII -Append
      # 调整私钥权限:移除继承权限,仅允许当前用户读取
      $acl = Get-Acl "$(Agent.HomeDirectory)\.ssh\id_rsa"
      $acl.SetAccessRuleProtection($true, $false)
      $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($env:USERNAME, "Read", "None", "None", "Allow")
      $acl.SetAccessRule($rule)
      Set-Acl "$(Agent.HomeDirectory)\.ssh\id_rsa" $acl
    displayName: '配置SSH密钥访问Bitbucket'
    shell: pwsh

  # windows-latest镜像自带Git,可省略此步骤
  # - script: choco install git -y
  #   displayName: '安装Git'

  - script: npm install
    displayName: '执行npm安装'

关键说明

  • 创建.ssh目录:用mkdir -Force确保目录存在,避免路径不存在的错误
  • 编码处理:使用PowerShell的Out-File并指定-Encoding ASCII,防止echo命令产生的编码问题导致SSH无法识别私钥
  • 权限设置:Windows下SSH要求私钥不能有过宽的权限,必须移除继承权限并仅给当前用户读权限,否则会触发权限拒绝错误
  • Git安装:windows-latest镜像默认已预装Git,无需额外通过choco安装

内容的提问来源于stack exchange,提问作者Sharon Watinsan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:53:06