ansible进阶版01
欢迎使用Markdown编辑器
最佳实践
保持简单
- 使用yaml的原生语法
- 使用自带模块
- 尽量使用专用模块,不要使用shell、script、command模块,因为这些模块没有幂等性。
- 使用标准风格
保持井然有序(有组织的)
- 使用友好的变量名:见文知义
- 保持项目有好的组织方式。例:
.
├── dbservers.yml
├── inventories/
│ ├── prod/
│ │ ├── group_vars/
│ │ ├── host_vars/
│ │ └── inventory/
│ └── stage/
│ ├── group_vars/
│ ├── host_vars/
│ └── inventory/
├── roles/
│ └── std_server/
├── site.yml
├── storage.yml
└── webservers.yml
- 如果可能,使用动态主机清单
- 适当的分组,利用分组的好处。一台主机可以属于多个组。
- 对于重复使用的内容,推荐使用角色role
- 集中运行playbook
经常测试
- 在playbook中包含测试代码
- 使用block/rescue实现任务补救
- 使用最新的Ansible版本
- 使用测试工具
git
- 是一个版本控制工具SCM
- 可以理解为,为目录打快照
工作原理
- 三个重要的工作区域
- 工作区:保存playbook等文件的目录
- 版本库:保存快照的目录。在工作区中名为
.git
的目录 - 暂存区:工作区和版本库之间的缓冲地带
文件的状态
- 未跟踪Untracked:工作区中的文件,既不在暂存区,又没有在版本库中
- 已暂存Staged:存入暂存区,尚未commit至版本库中的文件
- 未修改:版本库中的文件和工作区中的文件相同
- 已修改:文件被commit至版本库之后,有过改动
chapter 2
编写ymal格式的主机清单
- ansible支持多种格式的主机清单
[student@worktest ~]$ grep -A2 '^\[inventory' /etc/ansible/ansible.cfg
[inventory]
# enable inventory plugins, default: 'host_list', 'script', 'auto', 'yaml', 'ini', 'toml'
#enable_plugins = host_list, virtualbox, yaml, constructed
- yaml主机清单
# ini格式如下:
[lb_servers]
servera.lab.example.com
[web_servers]
serverb.lab.example.com
serverc.lab.example.com
[backend_server_pool]
server[b:f].lab.example.com
# 以上的ini格式,对应的yaml格式如下:
lb_servers:
hosts:
servera.lab.example.com:
web_servers:
hosts:
serverb.lab.example.com:
serverc.lab.example.com:
backend_server_pool:
hosts:
server[b:f].lab.example.com:
- 在ini格式的主机清单中,没有组名的主机,默认处于ungrouped组中。所有的主机,都在all组中。如notinagroup.lab.example.com在ungrouped组中:
notinagroup.lab.example.com
[mailserver]
mail.lab.example.com
# 以上ini格式对应的yaml如下:
all:
children:
ungrouped:
notinagroup.lab.example.com:
mailserver:
mail.lab.example.com:
- 主机清单变量
[monitoring]
watcher.lab.example.com
[monitoring:vars] # 组变量声明格式
smtp_relay: smtp.lab.example.com # 变量名: 变量值
# 以上ini格式对应的yaml格式如下:
monitoring:
hosts: # 定义组中的主机
watcher.lab.example.com:
vars: # 定义组变量
smtp_relay: smtp.lab.example.com
# ini主机变量示例:
[worktests]
worktest.lab.example.com
localhost ansible_connection=local # 主机变量
host.lab.example.com
# 以上ini格式对应的yaml格式如下:
worktests:
hosts:
worktest.lab.example.com:
localhost:
ansible_connection: local
host.lab.example.com:
- ansible为用户准备了将ini格式的清单转成yaml格式的命令:
[user@demo ~]$ ansible-inventory --yaml -i origin_inventory --list \
> --output destination_inventory.yml
# 注意,转成ymal格式的主机清单,有时候不准确,还需要手工调整。
vim技巧
[student@worktest inventory-yaml]$ vim ~/.vimrc
set ai # 自动缩进
set et # 将tab转为空格
set ts=2 # 按一个tab,缩进2个空格