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

Vagrant中移除代码内RH认证凭证的实现问题求助

解决Vagrant内联Provision脚本无法读取Secrets凭证的问题

问题背景

需移除Vagrantfile中硬编码的Red Hat用户名/密码,改用隐藏的secrets文件存储凭证,但配置后执行subscription-manager register时提示用户名/密码错误,核心问题是内联脚本未正确获取Secrets中的凭证值。

错误原因

修改后的Vagrantfile中,内联shell脚本直接写入Secrets::RH_username——这是Ruby语法,但shell环境无法识别,导致实际传递给subscription-manager的是字符串"Secrets::RH_username"而非真实凭证,最终认证失败。

修复方案

方案1:Ruby字符串插值传递凭证

沿用原有的字符串插值方式,将Secrets中的变量值直接插入到shell脚本内容中:

# .vagrant/secrets.rb
module Secrets
  RH_username = "XXXXX"
  RH_password = "XXXXX"
end
# 修改后的Vagrantfile
require_relative '.vagrant/secrets.rb'
include Secrets

# 用Ruby字符串插值生成带真实凭证的shell脚本
script = %{
if ! sudo subscription-manager status; then
  sudo subscription-manager register --username=#{RH_username} --password=#{RH_password}
fi
}

Vagrant.configure("2") do |config|
  (1..NODES).each do |i|
    config.vm.define "node#{i}" do |node|
      node.vm.provision "subscription-manager", type: "shell" do |subscription|
        subscription.inline = script
      end
    end
  end
end

方案2:通过环境变量传递凭证(更安全)

利用Vagrant的env参数将Ruby变量转为shell环境变量,脚本中通过环境变量引用,避免凭证直接出现在脚本内容中:

# 修改后的Vagrantfile
require_relative '.vagrant/secrets.rb'
include Secrets

Vagrant.configure("2") do |config|
  (1..NODES).each do |i|
    config.vm.define "node#{i}" do |node|
      node.vm.provision "subscription-manager", type: "shell" do |subscription|
        # 将Secrets中的凭证传递为shell环境变量
        subscription.env = {
          "RH_USERNAME" => RH_username,
          "RH_PASSWORD" => RH_password
        }
        subscription.inline = <<-SCRIPT
if ! sudo subscription-manager status; then
  sudo subscription-manager register --username="$RH_USERNAME" --password="$RH_PASSWORD"
fi
        SCRIPT
      end
    end
  end
end

注意事项

建议将secrets.rb放在项目根目录而非.vagrant下(.vagrant为Vagrant自动生成目录,可能被清理),并在.gitignore中添加secrets.rb避免提交到版本库。

内容的提问来源于stack exchange,提问作者gone t'pub

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:37:46