Weitere ähnliche Inhalte Ähnlich wie Ansibleで始めるインフラ構築自動化 (20) Ansibleで始めるインフラ構築自動化2. Profile
- 名前: 長原 佑紀 (Yuuki Nagahara)
- 所属: 株式会社ビズリーチ
- 部署: ビズリーチ事業 インフラ
- 経歴:
- 2007- SIer
- 2015- ビズリーチ
- 好き:
- AWS
- Android
11. - バージョン管理(Git)
- Pull Request(レビュー)
- TDI(TDD)(テスト駆動インフラストラクチャ)
- CI(継続的インテグレーション)
- CD(継続的デプロイ)
Infrastructure as Codeのプラクティス
12. Infrastructure as Codeの領域
システムコンフィグレーション
デプロイ、サーバ間連携
クラウド、VM、コンテナ、
OSインストール
オーケストレーション
(Orchestration)
コンフィグレーション
(Configuration)
ブートストラッピング
(Bootstrapping)
Fabric, Capistrano, Serf, Consol
Puppet, Chef, Ansible, Itamae
AWS, OpenStack, Docker,
KickStart, Cobbler, Terraform
15. ▷ ブートストラッピング
○ AWSのAPIを利用したEC2インスタンス管理
○ Dockerを利用したコンテナ管理
○ Vagrantでの仮想マシン立ち上げ
▷ コンフィグレーション
○ 各種ミドルウェアでのサーバの構築
○ パッチ適用
▷ オーケストレーション
○ アプリケーションの分散デプロイ(ローリングアップデート)
○ Hadoopクラスタの構築
○ メトリクス/監視ツールへのノード追加
ユースケース
19. ▷ Simple
- Yaml形式の設定ファイル
- 可読性高、コーディング不要
- 低い学習コスト
▷ Powerful
- "Batteries Included" (電池同梱)
- パッケージ1つで導入可能
▷ Agentless
- 構築対象にエージェントは不要
- sshが接続可能であれば良い
Ansibleの特徴
24. 構成管理ツール比較
Puppet Chef Ansible
開発言語 Ruby Ruby Python
開発開始 2005年 2009年 2012年
書式 独自DSL Ruby DSL yaml
冪等制 ◯ ◯ ◯
構成管理方法 Pull型 Pull型 Push型
エージェント 必要 必要 不要 ※1
※1: AnsibleもリモートホストにPython 2.4以降のインストールが予め必要。
27. Ansibleインストール
ansibleはyum、apt、pipで提供されているため環境に合わせてインストー
ル。
### Latest Release Via Yum (CentOS, RHEL)
$ yum install -y epel-release
$ sudo yum install ansible --enablerepo=epel
### Latest Releases Via Apt (Ubuntu)
$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible
### Latest Releases Via Pip (Linux, MacOS)
$ sudo easy_install pip
$ sudo pip install ansible
31. ansible-playbook コマンド
$ ansible-playbook -i hosts site.yml
PLAY [192.168.33.101] *************************************************
TASK [setup] *******************************************************************
ok: [192.168.33.101]
TASK [install nginx] ***********************************************************
changed: [192.168.33.101]
TASK [nginx running and enabled] ***********************************************
changed: [192.168.33.101]
PLAY RECAP *********************************************************************
192.168.33.101 : ok=3 changed=2 unreachable=0 failed=0
インベントリ
Playbook 初回実行時
32. ansible-playbook コマンド
$ ansible-playbook -i hosts site.yml
PLAY [192.168.33.101] *************************************************
TASK [setup] *******************************************************************
ok: [192.168.33.101]
TASK [install nginx] ***********************************************************
ok: [192.168.33.101]
TASK [nginx running and enabled] ***********************************************
ok: [192.168.33.101]
PLAY RECAP *********************************************************************
192.168.33.101 : ok=3 changed=0 unreachable=0 failed=0
再実行時
変更点なし
33. ansible-playbook コマンド
$ ansible-playbook -i hosts site.yml
… (snip) …
PLAY RECAP *********************************************************************
192.168.33.101 : ok=3 changed=2 unreachable=0 failed=0
結果 説明
ok 定義された状態となっている
changed 定義された状態に変更が行われた
unreachable リモートホストへの接続に失敗した
failed タスクの実行に失敗(エラー)
実行結果にて、各リモートホストの実行結果の要約(RECAP)を出力
34. PlaybookのDry Run
手動でPlaybookを流す前には必ず事前に意図した変更となるか確認する
ansible-playbook コマンド
$ ansible-playbook -i hosts site.yml --check
その他のオプション
-D, --diffオプション
ファイル等の変更差分内容を出力。
--syntax-check
playbookのシンタックスを検査。
--list-tasks
実行されるタスクの一覧を表示。
--start-at-taskオプション(=”task名”)
playbookを途中から実行する場合に有効。
--step
playbookを(N)o/(y)es/(c)ontinue入力でステップ実行。
Tips
Inventoryfileなしでplaybook実行
$ ansible-playbook -i "192.168.1.2," site.yml
※1台の場合は末尾にカンマが必要
37. 利用可能なモジュール一覧の確認
モジュールに関するドキュメントは`ansible-doc`コマンドで参照
Ansibleモジュール
$ ansible-doc -l
$ ansible-doc file
Sets attributes of files, symlinks, and directories, or removes
files/symlinks/directories. Many other modules support the same
options as the [file] module - including [copy], [template], and [assemble].
Options (= is mandatory):
- follow
This flag indicates that filesystem links, if they exist, should
be followed.
(Choices: yes, no)[Default: no]
- force
force the creation of the symlinks in two cases: the source file
does not exist (but will appear later); the destination exists
and is a file (so, we need to unlink the "path" file and create
モジュール名
39. ▷ setupモジュール(リモートホストの情報取得)
playbookの実行時は、デフォルトで始めに setupモジュールが実行されてファクト変数を取得
ファクト変数はplaybook内で変数として利用可( Distributionによる条件式等)
Ansibleモジュール
$ ansible 192.168.33.101 -i hosts -m setup --one-line
192.168.33.101 | SUCCESS => {"ansible_facts": {"ansible_all_ipv4_addresses": ["10.0.2.15",
"192.168.33.101"], "ansible_all_ipv6_addresses": ["fe80::a00:27ff:fe4f:b806",
"fe80::a00:27ff:fe03:c0a5"], "ansible_architecture": "x86_64", "ansible_bios_date": "12/01/2006",
"ansible_bios_version": "VirtualBox", "ansible_cmdline": {"KEYBOARDTYPE": "pc", "KEYTABLE":
"us", "LANG": "en_US.UTF-8", "SYSFONT": "latarcyrheb-sun16", "clocksource_failover":
"acpi_pm", "rd_NO_DM": true, "rd_NO_LUKS": true, "rd_NO_LVM": true, "rd_NO_MD": true, "ro":
true, "root": "UUID=1d798f26-8ace-413f-9530-2d1d1d4fdbb5"}, "ansible_date_time": {"date":
"2017-02-05", "day": "05", "epoch": "1486270715", "hour": "04", "iso8601":
"2017-02-05T04:58:35Z", "iso8601_basic": "20170205T045835431149",
"iso8601_basic_short": "20170205T045835", "iso8601_micro":
"2017-02-05T04:58:35.431233Z", "minute": "58", "month": "02", "second": "35", "time":
"04:58:35", "tz": "UTC", "tz_offset": "+0000", "weekday": "Sunday", "weekday_number": "0",
"weeknumber": "05", "year": "2017"}, "ansible_default_ipv4": {"address": "10.0.2.15", "alias":
"eth0", "broadcast": "10.0.2.255", "gateway": "10.0.2.2", …(snip)…
40. Ansibleモジュール
その他の代表的なモジュール
● file - ファイル/ディレクトリ作成や所有者/権限変更
● copy - リモートホストにファイルを転送
● template - テンプレートファイル(jinja2)を展開した
ファイルをリモートホストへ転送
● get_url - 指定URLからファイルをダウンロード
● lineinfile - リモートホストのファイルで正規表現にマッチ
する行の書き換え
● shell - シェルの実行
● yum / apt - パッケージ操作
● service - サービス操作
41. Role
Playbookを疎結合なコンポーネントの処理で分割したもの
tasks / defaults / files / templates / handlers / varsのディレクトリ構成
Roleを作成することで再利用可能となり、Playbookの可読性も高まる
site.yml # playbook
roles/nginx/ # roles/[Role名]ディレクトリ
├─ defaults/ # 変数のデフォルト値
| └ main.yml # Roleで利用する変数default
├─ files/ # copyモジュールのファイル
├─ handlers/ # 特定イベント発火タスク
| └ main.yml #
├─ meta/ # Roleのメタ情報(依存Role)
├─ tasks/ # Roleで実行されるタスク
| └ main.yml # 実行タスクファイル ※必須
├─ templates/ # templateモジュール
| └ xxx.xxx.j2 # Jinja2形式ファイル
└─ vars/ #
└ main.yml #
---
- hosts: web
roles:
- nginx nginxロール呼び出し
---
- name: install nginx
yum: name=nginx-{{ nginx_version }} state=present
- name: nginx running and enabled
service: name=nginx state=started enabled=yes
nginx_version: 1.10.2
42. vars / templates
varsはホスト/グループ/環境毎の設定値を定義、templates等にて変数代入
group_varsはグループ単位の設定値を変えることが可能
site.yml # playbook
hosts #インベントリ
group_vars
├─ web.yml # group: webのvars
├─ db.yml # group: dbのvars
roles
└─nginx/ # nginx rolesディレクトリ
├─ tasks/
| └ main.yml # roleの実行タスク
└─ templates/
└ index.html.j2 # index.htmlのテンプレート
- hosts: web
roles:
- nginx
- name: replace index.html
template:
src: index.html.j2
dest: /usr/share/nginx/html/index.html
name: “webserver”
group_vars name: {{ name }}
name: “dbserver”
$ ansible-playbook -i develop site.yml
$ ssh web01 “cat
/usr/share/nginx/html/index.html”
group_vars name: webserver
43. vars / templates
varsの値定義箇所は複数存在し、各優先度が複雑な為に注意が必要
● role defaults
● inventory vars
● inventory group_vars
● inventory host_vars
● playbook group_vars
● playbook host_vars
● host facts
● play vars
● play vars_prompt
● play vars_files
● registered vars
● set_facts
● role and include vars
● block vars (only for tasks in block)
● task vars (only for the task)
● extra vars (always win precedence)
low
priority
high
44. Ansible Vault
$ cat group_vars/webserver.vault
nginx_htpasswd: '9s36?;fyNp'
$ ansible-vault encrypt group_vars/webserver.vault
Encryption successful
$ cat group_vars/webserver.vault
$ANSIBLE_VAULT;1.1;AES256
61386434353264313436616339353933666163333931323262383
064343738643639373239643462
6665363764373265366464626666613535326531666363630a6
56332646462616231613438383233
... snip ...
### view encrypt vars file
$ ansible-vault view group_vars/webserver.vault
nginx_htpasswd: '9s36?;fyNp'
### edit encrypt vars file
$ ansible-vault edit group_vars/webserver.vault
### decrypt encrypted vars file
$ ansible-vault decrypt group_vars/webserver.vault
機密情報のvarsを暗号化してリポジ
トリ管理可能とするツール
playbook実行時にはパスワードに
より復号化して変数利用
パスワードファイル設置
ansible.cfgに以下の設定を追加
vault_password_file = ~/.vault_password
$ echo “passwd” > ~/.vault_password
46. Best Practice
production # inventory file for production servers
staging # inventory file for staging environment
group_vars/
group1 # here we assign variables to particular groups
group2 # ""
host_vars/
hostname1 # if systems need specific variables, put them here
hostname2 # ""
library/ # if any custom modules, put them here (optional)
filter_plugins/ # if any custom filter plugins, put them here (optional)
site.yml # master playbook
webservers.yml # playbook for webserver tier
dbservers.yml # playbook for dbserver tier
roles/
common/ # this hierarchy represents a "role"
tasks/ #
main.yml # <-- tasks file can include smaller files if warranted
handlers/ #
main.yml # <-- handlers file
templates/ # <-- files for use with the template resource
ntp.conf.j2 # <------- templates end in .j2
files/ #
bar.txt # <-- files for use with the copy resource
vars/ #
main.yml # <-- variables associated with this role
defaults/ #
main.yml # <-- default lower priority variables for this role
meta/ #
main.yml # <-- role dependencies
library/ # roles can also include custom modules
lookup_plugins/ # or other types of plugins, like lookup in this case
webtier/ # same kind of structure as "common" was above, done for the webtier
role
monitoring/ # ""
fooapp/ # ""
公式のAnsibleディレクトリ構成の
ベストプラクティス
マルチステージに対応
production / staging
49. Demo
(3) オーケストレーション
ローリングアップデートによるデプロイ
(2) コンフィグレーション
EC2のサーバ構築 x2台
common / ngnix
(1) ブートストラッピング
Ansibleを用いたAWSの環境構築
VPC / KeyPair / InternetGateway
Subnet / RouteTable / SecurityGroup /
EC2 x2台 / ELB
Availability Zone 1a Availability Zone 1c
web web
EC2 EC2
Elastic Load
Balancing
AWS via Ansible
● Rate exceededでAPI発行がこけることがある
(terraformは自動でリトライ)
● リソースを削除する場合には state: absentのPlaybookが別途必要
(terraformはdestroyで一括削除)
● AWSサービスのモジュールサポートは事前に要チェック
(デモ範囲は全てモジュールで実現)
51. - バージョン管理(Git)
- Pull Request(レビュー)
- TDI(TDD)(テスト駆動インフラストラクチャ)
- CI(継続的インテグレーション)
- CD(継続的デプロイ)
(再) Infrastructure as Codeのプラクティス
52. - バージョン管理(Git)
- Pull Request(レビュー)
- TDI(TDD)(テスト駆動インフラストラクチャ)
- CI(継続的インテグレーション)
- CD(継続的デプロイ)
(再) Infrastructure as Codeのプラクティス
55. Pull Request(レビュー)
## 概要
xxx
## レビュー観点
- xxx
## 環境適用手順
### ローカル環境
```
ansible-playbook -i inventories/local/hosts
playbooks/xxx.yml --diff --check
```
### 検証環境
```
ansible-playbook -i inventories/develop/hosts
playbooks/xxx.yml --diff --check
```
### 本番環境
```
ansible-playbook -i inventories/production/hosts
playbooks/xxx.yml --diff --check
```
## CIテスト実行設定
- テスト実行可否 [true/false]
test-enable: true
- テスト対象Playbook [csv形式]
test-playbooks: webservers.yml, dbservers.yml
## サービスへの影響
xxxx
## レビュー期日
xx/xx
.github/PULL_REQUEST_TEMPLATE.mdを作成することでPR作成簡略化
58. CI(継続的インテグレーション)
(4) launch instances
and exec playbook
(run, dry-run, run)
(1) pull request
push
(2) webhook
Jenkins
test script
test script
(3) exec
playbooks x procs
(6) post results
(7) result
(5) notify
EC2
EC2
62. 機能
▷ ビジュアルダッシュボード
▷ ロールベースのアクセス制御
▷ ジョブスケジューリング
▷ グラフィカルな在庫管理
▷ リアルタイムでの
ジョブステータス更新
https://www.redhat.com/ja/technologies/management/ansible
Ansible Tower
Ansibleの管理・操作用のWeb GUI インタフェース。
10ホストまでは無料、それ以上は有償。
ホストの状態はAnsible Towerでも管理可能。