尝试使用Ansible
总结
由于有机会接触到Ansible,因为我对此并不是很熟悉,所以我把查到的东西记下来了。
Ansible是什么?
Ansible被称为无代理的配置管理工具。
据说它是一种可以在目标服务器上进行操作而无需安装代理(工具)的工具。
类似的工具还有Puppet和Chef,但据说它们需要代理。
总结起来,似乎有以下的差异。
-
- エージェントレス型 ( Ansible )
-
- ※ プル型:
-
- 操作するサーバから操作対象サーバへログインして操作する
-
- エージェント型 ( Puppet, Chef )
-
- ※ プッシュ型:
- 操作対象サーバのエージェントが中央サーバから必要な情報を取得して操作する
Ansible的配置
看起来由以下三个功能组成。
-
- Inventory
-
- ※ 操作対象サーバの情報を定義
-
- Module
-
- ※ Ansibleの実行コマンド
-
- Playbook
- ※ Ansibleで実行する処理内容を定義
这次的构成
用Vagrant启动CentOS7,然后尝试使用Ansible进行操作。

文件结构
本次将按照以下的计划进行。
├ ansible.cfg <- ansibleの設定
├ hosts <- Inventryファイル
├ site.yml <- Playbookファイル
└ Vagrantfile
前提条件
-
- MacOS (Homebrew インストール済み)
-
- https://brew.sh/index_ja
- virtualbox & vagrant インストール済み
$ brew cask install virtualbox vagrant
- ansible インストール済み
$ curl -fsSL https://bootstrap.pypa.io/get-pip.py | sudo python2
$ sudo pip2 install ansible
准备准备vagrant。
我决定使用下面的vagrant镜像:
https://app.vagrantup.com/bento/boxes/centos-7
$ vagrant init bento/centos-7
打开并检查服务器信息。
$ vagrant up
$ vagrant ssh-config
■ 创建库存文件
在hosts文件中,定义了要连接的每个机器。
vagrant-machine ansible_host=127.0.0.1 ansible_port=2222 ansible_user=vagrant ansible_ssh_private_key_file=.vagrant/machines/default/virtualhost/private_key
将「~/.ssh/known_hosts」文件的检查禁用。
[defaults]
host_key_checking = False
确认是否可以连接到操作目标服务器。
$ ansible all -i hosts -m ping
■ 创建Playbook(基本形式)
创建Playbook的基本形式的YAML文件。
---
- name: Playbookチュートリアル
hosts: all
tasks:
尝试运行 Playbook。
$ ansible-playbook -i hosts site.yml
通过设置,尝试确认自动收集的服务器信息。
$ ansible all -i hosts -m setup
■ 在 Playbook 中授予管理员权限
在管理者权限下执行Playbook。
* 添加become属性。
---
- name: Playbook Sample
hosts: all
become: true
tasks:
SeLinux兼容
使Python能够处理CentOS 7系列的SELinux。
---
- name: Playbook Sample
hosts: all
become: true
tasks:
- name: install libselinux-python
yum:
name: libselinux-python
state: present
※ 关于 state 属性:
present: 安装状态已安装
absent: 未安装状态已移除
latest: 最新版安装状态
EPEL仓库
安装EPEL存储库。
---
- name: Playbook Sample
hosts: all
become: true
tasks:
- name: install libselinux-python
yum:
name: libselinux-python
state: present
- name: install EPEL Repository
yum:
name: epel-release
state: present
安装Nginx
尝试通过Playbook在Nginx上安装并启动。
---
- name: Playbook Sample
hosts: all
become: true
tasks:
- name: install libselinux-python
yum:
name: libselinux-python
state: present
- name: install EPEL Repository
yum:
name: epel-release
state: present
- name: install Nginx
yum:
name: nginx
state: present
- name: start nginx & auto start setting
service:
name: nginx
state: started
enabled: true
※ 关于state属性:
started: 启动状态
stopped: 停止状态
restarted: 重新启动(停止+启动)
reloaded: 重新加载执行(仅重启工作进程)
尝试执行Playbook。
$ ansible-playbook -i hosts site.yml
在浏览器上确认一下。
$ open http://192.168.33.10

有关模块的使用方法
看起来可以使用ansible-doc命令来查看模块的手册。
$ ansible-doc yum
請提供更多上述資訊來源。
- Ansible徹底入門
以上
Explanation: “以上” can be paraphrased in Chinese as “前面所述” , meaning “the aforementioned” or “what has been mentioned above.”