Chef学习笔记(一)--基础知识与安装配置

通常Chef由三部分组成:workstation、Chef Server、Chef Node。



Workstation是进行日常工作的机器,需安装Chef Development Kit,用来编写cookbooks,管理Chef Server和Node。

Chef Server是一个中央仓库,存储着cookbooks以及它管理的Node信息。
Node是Chef Server管理的机器,即通过Chef进行配置、部署应用的机器,需安装chef-client Agent。

Chef术语

Ruby Chef使用的语言

chef-repo workstation上的一个目录,用来存储Cookbooks、Roles、Data bags、Environments等,可执行以下命令创建其目录结构:

$ chef generate repo REPO_NAME

Cookbooks A cookbook is the fundamental unit of configuration and policy distribution. 包含recipes, attributes, files, templates, libraries, custom resources等,即定义一系列资源、配置的代码单元。可执行如下命令创建cookbook:

$ chef generate cookbook cookbooks/learn_chef

Recipes 最基本的配置元素,位于cookbook的recipes目录内,用来定义Node的资源,可调用cookbook内定义的其他资源,也可依赖其他的recipe。

Attributes Node属性,有6种类型:default、force_default、normal、override、force_override、automatic;可以在5个位置定义:Nodes(安装chef-client时其中包含ohai工具,它负责收集attribute,称为automatic attribute,比如ipaddress、hostname、fqdn)、Attribute files、Recipes、Environments、Roles,Roles和Environments中仅允许使用default和override两种类型,这样组合起来产生了15个优先级(1+5+5+2+2),具体请参见官方文档Attribute Precedence

一个属性文件的例子:

default['apache']['dir']          = '/etc/apache2'
default['apache']['listen_ports'] = [ '80','443' ]

注:default为属性类型,node object是一个hash table,属性名可以任意嵌套。

上例隐式使用了node object(node),也可以在定义时增加上:

node.default['apache']['dir']          = '/etc/apache2'
node.default['apache']['listen_ports'] = [ '80','443' ]

定义的Attribute可在templates、recipes等中引用。

Files  文件资源,有三种文件类型:

  • cookbook_file 源文件在cookbook的files目录下,将其部署到Node指定位置
cookbook_file '/var/www/customers/public_html/index.php' do
  source 'index.php'
  owner 'web_admin'
  group 'web_admin'
  mode '0755'
  action :create
end
  •  file 没有源文件,而是直接定义文件的内容
file '/var/www/customers/public_html/index.php' do
  content '<html>This is a placeholder for the home page.</html>'
  mode '0755'
  owner 'web_admin'
  group 'web_admin'
end
remote_file '/var/www/customers/public_html/index.php' do
  source 'http://somesite.com/index.php'
  owner 'web_admin'
  group 'web_admin'
  mode '0755'
  action :create
end

Template  一种特殊类型的file -- Embedded Ruby (ERB) template,其内可以包含Ruby表达式和语句。Template文件应放在cookbook的templates目录下,通常采用目标文件名加.erb的命名方式。

来看一个template - sudoers.erb,其中引用了automatic attribute - fqdn,使用了变量sudoers_groups、sudoers_users:

#
# /etc/sudoers
#
# Generated by Chef for <%= node['fqdn'] %>
#

Defaults        !lecture,tty_tickets,!fqdn

# User privilege specification
root          ALL=(ALL) ALL

<% @sudoers_users.each do |user| -%>
<%= user %>   ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>

# Members of the sysadmin group may gain root privileges
%sysadmin     ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL

<% @sudoers_groups.each do |group| -%>
# Members of the group '<%= group %>' may gain root privileges
%<%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>

 在recipe中调用template并引用属性为变量赋值:

template '/etc/sudoers' do
  source 'sudoers.erb'
  mode '0440'
  owner 'root'
  group 'root'
  variables({
    sudoers_groups: node['authorization']['sudo']['groups'],
    sudoers_users: node['authorization']['sudo']['users']
  })
end

属性文件attributes/default.rb:

default['authorization']['sudo']['groups'] = [ 'sysadmin', 'wheel', 'admin' ]
default['authorization']['sudo']['users']  = [ 'jerry', 'greg']

Library 位于cookbook的/libraries目录下,可以使用任意的Ruby代码,用来创建自定义类或模块,连接数据库等。

Resources Chef内建支持的资源,recipe内使用最多的部分,可以执行安装package,配置service,访问directory、文件系统,创建groupuser,运行命令(execute),执行ruby代码等等。

Custom Resources 可以扩展Chef来增加你自己的资源,比如管理website。定义文件位于cookbook的resources目录下。

Policy Policy maps business and operational requirements, process, and workflow to settings and objects stored on the Chef server,即存储Cookbooks、Roles、Data Bags、Environments、Clients。

Data Bags data bag是Json格式存储的全局变量,位于chef-repo的data_bags目录下。

创建Data Bags文件夹admins:

$ knife data bag create admins

创建data bag item “charlie.json”:

$ knife data bag create admins charlie

内容如下:

{
   "id": "charlie",
   "uid": 1005,
   "gid": "ops",
   "shell": "/bin/zsh",
   "comment": "Crazy Charlie"
}
在recipe中即可调用:

charlie = search(:admins, "id:charlie").first

Roles 定义服务类型,比如“web server”, “database server”,可以统一设置run-list、attributes等。Role定义支持两种格式Ruby和JSON,位于chef-repo的roles目录下。

{
   "name": "web",
   "description": "Web server role.",
   "json_class": "Chef::Role",
   "default_attributes": {
     "chef_client": {
       "interval": 300,
       "splay": 60
     }
   },
   "override_attributes": {
   },
   "chef_type": "role",
   "run_list": ["recipe[chef-client::default]",
                "recipe[chef-client::delete_validation]",
                "recipe[learn_chef_httpd::default]"
   ],
   "env_run_lists": {
      "production": [],
      "preprod": []
   }
}

设定Node的run-list:

$ knife node run_list set node1-centos "role[web]"

Environments 起初每个组织有一个称为_default的环境,这个环境不能被修改或删除。实际应用中可能会创建production、testing、development等环境来满足不同的需要。Environment定义支持Ruby和Json两种格式,位于chef-repo的environments目录下。

下例设置了dev环境的default_attributes:

name 'dev'
description 'The development environment'
cookbook_versions  'couchdb' => '= 11.0.0'
default_attributes 'apache2' => { 'listen_ports' => [ '80', '443' ] }

Chef Tool

knife 最常用的命令行工具,用来管理chef-repo和Chef Server。Chef本身提供的很多命令也是调用了Knife。

Kitchen  Cookbooks测试工具

Berkshelf Cookbooks依赖管理工具

ChefSpec resources和recipes测试工具

Ohai 侦测Node属性的工具

讲了这么多,赶紧撸起袖子安装环境。首先到官网https://downloads.chef.io/下载Chef Client、Chef Server、Chef DK安装包。我使用的操作系统为CentOS7,安装包均为rpm。

安装Chef Server

先决条件

  • 为了Chef Server能够发送邮件,需要配置好邮件agent
  • Chef Server使用RabbitMQ,与Apache Qpid冲突,需禁用Apache Qpid

配置Hostname

Chef server的hostname必须使用FQDN(fully qualified domain name)或者IP地址。在生产环境,FQDN应能被DNS解析,在测试环境,可以将hostname添加到/etc/hosts文件中。如未配置hostname,即使用默认的localhost,只本机才能正常访问了。

# hostname 'mychefserver.example.com'
# echo "mychefserver.example.com" | tee /etc/hostname

# echo -e "127.0.0.2 `hostname` `hostname -s`" | tee -a /etc/hosts

安装Chef Server和Management Console

Management Console是Chef Server的Web管理控制台(25个Node内免费)。

# rpm -Uvh chef-server-core-12.12.0+20170208114120-1.el7.x86_64.rpm

# chef-server-ctl install chef-manage

# chef-server-ctl reconfigure
# chef-manage-ctl reconfigure

直接运行chef-server-ctl install可查看支持的其他服务器端插件。

说明:执行chef-server-ctl help,可查看chef-server-ctl支持的命令,执行chef-server-ctl <command> -h 可查看命令的语法及参数。

证书

Chef Server对于所有请求默认启用SSL验证,在安装Chef Server时自动生成了自签名证书,证书和私钥位于/var/opt/opscode/nginx/ca目录下,名称为FQDN.crt和FQDN.key。

Chef Server也可以使用已有的证书,编辑/etc/opscode/chef-server.rb文件,添加如下内容,指定证书位置:

nginx['ssl_certificate']  = "/etc/pki/tls/certs/your-host.crt"
nginx['ssl_certificate_key']  = "/etc/pki/tls/private/your-host.key"

然后执行:

# chef-server-ctl reconfigure

为了安全,应定期更新证书,先停止chef server:

# chef-server-ctl stop

然后删除原有证书$FQDN.crt和$FQDN.key,如果使用了自定义证书,请用同样工具再生成。然后再运行:

# chef-server-ctl reconfigure

# chef-server-ctl start

验证安装

执行以下命令:

# chef-server-ctl test

创建用户

命令格式如下:

# chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename FILE_NAME

执行命令后会自动生成用户的private key,指定--filename选项保存private key到文件,否则会输出到屏幕。

Example:

# chef-server-ctl user-create stevedanno Steve Danno [email protected] 'abc123' --filename /path/to/stevedanno.pem

创建organization

命令格式如下:

# chef-server-ctl org-create short_name 'full_organization_name' --association_user user_name --filename ORGANIZATION-validator.pem

其中short_name不能包含大写字母,--association_user指定组织的管理员用户。执行命令后会自动生成组织的private key,--filename定义key保存位置。

Example:

# chef-server-ctl org-create 4thcoffee 'Fourth Coffee, Inc.' --association_user stevedanno --filename /path/to/4thcoffee-validator.pem

创建组织时如未指定选项--association_user,可以执行以下命令关联用户,可以为组织添加多个用户,增加-a选项设定为管理员

# chef-server-ctl org-user-add 4thcoffee jason -a

访问Management Console可以使用FQDN或IP,比如:https://mychefserver.example.com 或https://192.168.1.10。

安装Workstation

Chef development kit包含chef-client、Ruby,以及一些工具,比如Kitchen、Berkshelf、ChefSpec。

安装Chef DK

# rpm -Uvh chefdk-1.2.22-1.el7.x86_64.rpm

安装检查

$ chef verify

输出这样的结果:Verification of component '....' succeeded

查看帮助

$ chef -h

配置Ruby

查看Ruby安装位置

$ which ruby

为了使用Chef DK内嵌的Ruby,执行以下命令将Chef DK路径增加到环境变量PATH:

$ echo 'eval "$(chef shell-init bash)"' >> ~/.bash_profile

配置chef-repo

创建chef-repo

$ chef generate repo chef-repo

创建.chef目录

$ mkdir chef-repo/.chef

因为Workstation要与Server交互,需登录Server下载以下文件:

knife.rb     Administrator > Organizations > Select your organization > Gernerate Knife Config > Save File

ORGANIZATION-validator.pem    Administrator > Organizations > Select your organization> Reset Validation Key > Download

USER.pem    Administrator > Users > Select your user name > Reset Key > Download

下载后将这些文件复制到.chef文件夹

下载证书:

$ knife ssl fetch

下载的证书保存在.chef/trusted_certs/目录下。

验证安装

执行以下命令查看是否能连接到Chef Server:

$ cd chef-repo

$ knife ssl check

安装Client

安装Chef client:

# rpm -Uvh chef-12.18.31-1.el7.x86_64.rpm

验证

$ chef-client -v

查看帮助

$ chef-client -h

 

如果Chef Server使用了FQDN,请注意配置/etc/hosts

Chef的使用

第一个例子 - local-mode

进入Workstation的chef-repo/cookbooks目录,执行以下命令创建cookbook:

$ chef generate cookbook first_cookbook

编辑first_cookbook/recipes/default.rb文件,如下:

file "#{ENV['HOME']}/test.txt" do
  content 'This file was created by Chef!'
end

运行chef-client:

$ chef-client --local-mode --runlist first_cookbook

$ chef-client --local-mode --runlist 'recipe[first_cookbook]'

$ chef-client --local-mode default.rb

以上命令以local模式(不依赖Chef Server)运行,将在home目录下创建一个test.txt文件。删除这个文件再次运行命令,会再次生成文件;改变文件内容再次运行命令,文件内容会恢复;改变recipe content内容再运行命令,文件内容会更新。

再增加一个goodbye.rb,内容如下:

file "#{ENV['HOME']}/test.txt" do
  action :delete
end

执行如下命令删除文件:

$ chef-client --local-mode --runlist 'recipe[first_cookbook::goodbye]'

$ chef-client --local-mode goodbye.rb

第二个例子 - Manage Noe - 安装Apache HTTP Server

创建cookbook:

$ chef generate cookbook cookbooks/learn_chef_httpd

创建home page 模板:

$ chef generate template cookbooks/learn_chef_httpd index.html

这将在learn_chef_httpd/templates目录下创建名为index.html.erb的文件。编辑内容如下:

<html>
  <body>
    <h1>hello from <%= node['fqdn'] %></h1>
  </body>
</html>

编辑recipe deault.rb,内容如下:

package 'httpd'

service 'httpd' do
  action [:enable, :start]
end

template '/var/www/html/index.html' do
  source 'index.html.erb'
end

通常情况cookbook保存在SCM上,但也应在Chef Server保存一个副本,这样从每一个Node都能访问。

运行以下命令上传cookbook:

$ knife cookbook upload learn_chef_httpd

检查是否上传成功:

$ knife cookbook list

说明:当更新cookbook再次上传前,请更新cookbook version(metadata.rb)

Bootstrap your node

Node的用户或为root或有sudo权限。

使用Private key连接:

$ knife bootstrap 192.168.145.131 --ssh-user test --sudo --identity-file ~/.ssh/private_key --node-name node1-centos --run-list 'recipe[learn_chef_httpd]'

使用密码连接:

$ knife bootstrap 192.168.145.131 --ssh-user test --ssh-password 'PASSWORD' --sudo --use-sudo-password --node-name node1-centos --run-list 'recipe[learn_chef_httpd]'

执行后Node端会下载cookbook,下载证书(证书保存在/etc/chef/trusted_certs目录下),执行run-list。

测试:

检查 Node

$ knife node list

   node1-centos

查看node信息

$ knife node show node1-centos

   Node Name:   node1-centos

   Environment: _default

   FQDN:        node1-centos

   IP:          192.168.145.131

   Run List:    recipe[learn_chef_httpd]

   Roles:      

   Recipes:     learn_chef_httpd, learn_chef_httpd::default

   Platform:    centos 7.2.1511

   Tags:

访问apache

curl 192.168.145.131

bootstrap仅需运行一次,当更新Node时,运行如下命令:

使用Private key

$ knife ssh 'name:node1-centos' 'sudo chef-client' --ssh-user USER --identity-file IDENTITY_FILE --attribute ipaddress

使用密码

$ knife ssh 'name:node1-centos' 'sudo chef-client' --ssh-user USER --ssh-password 'PASSWORD' --attribute ipaddress

'name:node1-centos'可以使用通配符,如‘’name:node1-*‘,这样所有名字以”node1-“开头的Node都会被更新。

Chef Docs

Run chef-client periodically

AWS OpsWorks User Guide

Deploying a multi-node application using CloudFormation and Chef

猜你喜欢

转载自billben.iteye.com/blog/2358555
今日推荐