3

Ansible初体验

 3 years ago
source link: https://note.qidong.name/2018/10/ansible/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Ansible初体验

2018-10-11 22:09:05 +08  字数:1221  标签: Ansible Linux

Future of Automation

Ansible简介

Ansible是一个自动化运维工具。 它能批量配置系统、部署软件,也能编排更复杂的运维任务,如连续部署、零停机时间滚动更新等。 同类软件有SaltPuppetChef等,都各有优劣。 而Ansible独特的优势在于,只要配置SSH能免密连接就行(通过paramiko实现),无需配置Agent。

Ansible是基于模块(Module)工作的,本身没有批量部署的能力。真正具有批量部署的是Ansible所运行的模块,Ansible只是提供一种框架。 目前,Ansible版本为2.6.5,支持1850个模块。 模块也可称为插件(Plugin),可以自定义,按需开发,因此Ansible也具备非常良好的可扩展性。

安装Ansible

Ansible是一个Python项目,可以直接通过pip安装。

pip install ansible

当然,这样虽然简单方便,却没有CLI补全支持。 所以,也可以通过包管理器安装。

# For Debian/Ubuntu
sudo apt install ansible
# For Mac OS X
brew install ansible

配置文件

Ansible的配置文件有多个,按优先级排序如下:

  • ANSIBLE_CONFIG (环境变量,如果不为空则最优先)
  • ansible.cfg (当前路径下的配置)
  • ~/.ansible.cfg (用户主目录下)
  • /etc/ansible/ansible.cfg (全局配置文件)

这里有一个官方样例:ansible.cfg。 将其复制到本地的~/.ansible.cfg,略作修改,即可开始体验。 说到底,配置文件这种东西,最高效的使用方法,就是从一个注释完善的模板开始定制。

curl -sSL https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg -o ~/.ansible.cfg

Inventory

Inventory中,定义了被托管host的集合。 可以使用域名、hostname等,能够查询到IP的字符串,或者IP本身。 格式类似ini,但保留all字段,这代表全部。

[xx]
10.0.0.73
10.0.0.74
10.0.0.75
10.0.0.76
10.0.0.77
10.0.0.78
10.0.0.79
10.0.0.80

测试

$ ansible xx -m ping
10.0.0.77 | FAILED! => {
    "changed": false,
    "module_stderr": "Shared connection to 10.0.0.77 closed.\r\n",
    "module_stdout": "/bin/sh: 1: /usr/bin/python: not found\r\n",
    "msg": "MODULE FAILURE",
    "rc": 127
}
...

以上为失败的测试。 除了Master的SSH的公钥要配置到Slave的~/.ssh/authorized_keys以外,Slave还需要安装Python。

以下为成功的测试。 成功后,就可以开始执行正式的操作。

$ ansible xx -m ping
10.0.0.77 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
...

常用操作

# 安装htop
ansible xx -m apt -a 'name=htop'
# 卸载htop
ansible xx -m apt -a 'name=htop state=absent'

# 复制一个文件到所有目标位置
ansible xx -m copy -a 'src=sth.zip dest=/tmp/'

# 修改某个文件的权限与所属
ansible xx -u root -m file -a 'dest=/tmp/sth.zip mode=777 owner=root group=docker'

总体来说,用法还是很鬼畜的,其实是手写Playbook。 所以,除了临时操作,还是转为写ansible-playbook会比较专业。 (本文不对ansible-playbook做介绍。)

另外,执行任意命令也是可以的,但慎用:

ansible xx -a 'echo hello'

这样做,虽然也能达到和模块相同的功能,但却不能支持良好的执行过程管理,不能回滚,也不能避免重复。 因此,还是需要尽量使用模块来完成任务。

交互式教程

turkenh/ansible-interactive-tutorial是GitHub上的一个交互式教程。 通过CLI的形式,给出提示、进行指导。 新手只需要亦步亦趋地跟着做,就会自然入门Ansible

git clone https://github.com/turkenh/ansible-interactive-tutorial.git
cd ansible-interactive-tutorial
./tutorial.sh
demo

参考


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK