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

Chef环境下如何跳过已存在的指定版本amazon-ssm-agent安装?

How to Skip Amazon SSM Agent Installation When Specific Version Already Exists

嘿,我来帮你搞定这个问题!要在Chef Cookbook里跳过已存在的特定版本SSM代理安装,关键是利用Chef的not_if条件语句,精准检查系统中是否已经安装了目标版本的包,避免重复执行下载和安装操作。

首先纠正你原代码里的一个小问题:execute块里直接写rpm -qa | grep ssm是不符合Ruby语法的,条件判断应该放在not_if或only_if属性里。

下面是修改后的完整Cookbook代码,两种写法供你选择:

写法一:提前定义检查变量(可读性更强)

# 提前检查系统是否已安装指定版本的SSM代理
ssm_target_version_installed = Mixlib::ShellOut.new('rpm -q amazon-ssm-agent-2.2.355.0-1.x86_64').run_command.exitstatus == 0

remote_file '/tmp/amazon-ssm-agent.rpm' do
  source 'https://s3.amazonaws.com/SMAgent/linux_amd64/amazon-ssm-agent.rpm'
  action :create
  # 仅当未安装目标版本时才下载RPM包
  not_if { ssm_target_version_installed }
  notifies :run, 'execute[amazon-ssm-agent-install]', :immediately
end

execute 'amazon-ssm-agent-install' do
  command 'rpm -ivh /tmp/amazon-ssm-agent.rpm'
  action :nothing
  # 仅当未安装目标版本时才执行安装命令
  not_if { ssm_target_version_installed }
end

写法二:直接在条件中写命令(更简洁)

remote_file '/tmp/amazon-ssm-agent.rpm' do
  source 'https://s3.amazonaws.com/SMAgent/linux_amd64/amazon-ssm-agent.rpm'
  action :create
  # 用rpm -q精确检查目标版本是否存在,存在则跳过下载
  not_if 'rpm -q amazon-ssm-agent-2.2.355.0-1.x86_64'
  notifies :run, 'execute[amazon-ssm-agent-install]', :immediately
end

execute 'amazon-ssm-agent-install' do
  command 'rpm -ivh /tmp/amazon-ssm-agent.rpm'
  action :nothing
  # 同样的条件,确保只有未安装时才执行安装
  not_if 'rpm -q amazon-ssm-agent-2.2.355.0-1.x86_64'
end

原理说明

rpm -q <完整包名+版本>命令会在包已安装时返回退出码0,未安装时返回非0。Chef的not_if属性会在命令返回0时跳过对应资源的执行,正好实现了“已安装指定版本则跳过下载和安装”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:24:26