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

Chef Infra冗余用户删除技术咨询:编写Recipe清理指定用户

问题:Chef Infra无法删除冗余用户及批量清理方案

问题背景

刚接触Chef Infra,需清理500台VM中的10个冗余用户,确保无残留。当前通过GitLab管理chef01-cookbooks/bags/users下的用户JSON配置,已在冗余用户(如john.deer)的配置中添加"action":"remove",但执行chef-client后用户未被删除,日志显示仍在执行创建操作。需在chef01-cookbooks/cookbooks/users/recipes/下创建仅执行删除的Recipe,精准清理指定用户且不影响正常用户。

现有配置与日志

创建用户的Recipe(create_cto.rb)

#service 'nslcd' do
# action [ :stop ]
#end

unless node['platform'] == 'windows'

users_manage 'fgp' do
  group_id 9999
  action [:create, :remove]
  data_bag 'users'
end

#users_manage 'dev' do
# group_id 500
# action [:create, :remove]
# data_bag 'users'
#end

冗余用户JSON配置

{
  "id": "user.name",
  "username": "john.deer",
  "comment": "xxccc",
  "shell":"/dev/null",
  "groups": [
    "fgp"
  ],
  "action":"remove",
  "ssh_keys": [
    "disable"
  ]
}  

正常用户JSON配置

{
   "id": "johndo",
   "username": "johndo",
   "comment": "john",
   "groups": [
     "fgp"
   ],
   "ssh_keys": [
     "ssh-rsa AAAAB... .... ...t"
   ]
}

chef-client执行日志

* group[john.deer] action create (skipped due to only_if)
* linux_user[john.deer] action create (up to date)
* directory[/home/john.deer/.ssh] action create (up to date)
* template[/home/john.deer/.ssh/authorized_keys] action create (up to date)

问题诊断

  1. users_manage资源的action [:create, :remove]会优先执行创建逻辑,且默认不识别data bag中的action字段来区分用户操作
  2. 尝试的删除Recipe存在语法错误(缺少end),且users_manage :remove会删除所有关联到fgp组的用户,无法实现精准删除需求

解决方案

场景1:精准删除指定10个用户(推荐)

创建独立的删除Recipe,直接针对目标用户执行删除,完全不影响正常用户:

路径:chef01-cookbooks/cookbooks/users/recipes/cleanup_redundant_users.rb

unless node['platform'] == 'windows'
  # 列出需要删除的10个冗余用户名
  redundant_users = %w(john.deer user2 user3 user4 user5 user6 user7 user8 user9 user10)

  redundant_users.each do |username|
    linux_user username do
      action :remove
      manage_home true # 可选:同时删除用户主目录
    end

    # 清理用户私有组(若存在)
    group username do
      action :remove
    end
  end
end
  • 仅遍历指定的10个用户,逐个执行删除操作
  • manage_home true可按需开启,用于清理用户主目录

场景2:修复data bag驱动的删除逻辑

若需保留data bag的管理方式,需调整users_manage的过滤规则,分离删除与创建逻辑:

unless node['platform'] == 'windows'
  # 仅处理需要删除的用户
  users_manage 'fgp_remove' do
    group_id 9999
    action [:remove]
    data_bag 'users'
    filter { |user| user['action'] == 'remove' }
  end

  # 仅处理正常用户的创建
  users_manage 'fgp_create' do
    group_id 9999
    action [:create]
    data_bag 'users'
    filter { |user| user['action'].nil? || user['action'] != 'remove' }
  end
end
  • 通过filter方法分别筛选需删除和需保留的用户,避免操作冲突

执行与验证

  1. 将新Recipe添加到目标节点的run_list,或通过工具批量更新500台VM的run_list
  2. 执行chef-client,查看日志确认删除操作执行成功:
    * linux_user[john.deer] action remove (up to date)
    * group[john.deer] action remove (up to date)
    
  3. 在VM上验证用户状态:执行id john.deer,应返回用户不存在的提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:45:40