Chef 是一种基础设施即代码(Infrastructure as Code, IaC)工具,用于自动化服务器配置、应用部署和系统管理。下面从核心概念 → 安装 → 基本使用流程 → 示例 → 最佳实践给你一个完整入门指南。
| 名称 | 说明 |
|---|---|
| Cookbook | 配置的基本单元(类似“模块”) |
| Recipe | 具体配置脚本(Ruby 语法) |
| Resource | 配置对象(如 package、service、file) |
| Attribute | 节点变量(可覆盖) |
| Role | 定义一类服务器的配置集合 |
| Data Bag | 存储敏感/共享数据(如密码) |
curl -L https://omnitruck.chef.io/install.sh | sudo bash -s -- -P chef-workstation
验证:
chef --version
sudo chef-server-ctl reconfigure
curl -L https://omnitruck.chef.io/install.sh | sudo bash
chef generate repo my_infra
cd my_infra
chef generate cookbook cookbooks/nginx
目录结构:
nginx/
├── recipes
│ └── default.rb
├── attributes
├── templates
└── metadata.rb
recipes/default.rbpackage 'nginx' do
action :install
end
service 'nginx' do
action [:enable, :start]
end
file '/var/www/html/index.html' do
content '<h1>Hello from Chef</h1>'
end
knife cookbook upload nginx
knife bootstrap 192.168.1.10 \
-x ubuntu -P password \
-N web-server-01
knife node run_list add web-server-01 'recipe[nginx]'
在节点上:
sudo chef-client
knife role create web
web.rb:
name "web"
run_list "recipe[nginx]"
应用:
knife node run_list set web-server-01 'role[web]'
user 'deploy' do
action :create
end
directory '/opt/app' do
owner 'deploy'
mode '0755'
end
template '/etc/nginx/nginx.conf' do
source 'nginx.conf.erb'
end
✅ 使用 Cookbook + Role 分层管理
✅ 敏感信息放 Data Bag / Vault
✅ 使用 Test Kitchen 做本地测试
✅ CI/CD 中自动 chef-client
✅ 避免手写 Shell,用 Resource
如果你愿意,我可以:
你想从哪一步继续?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。