AnsibleでShellScriptをリモート実行
前回までで、AnsibleのPlaybookは比較的簡単に作れることが分かった。けれども結局はYAMLファイルを独自に作りこまないといけないから、過去の資産をそのまま活かすのは難しい。ということで、一般的なShellScriptをAnsibleでリモート環境に送り込んでリモートで実行する方法を試してみる。
サンプルスクリプト
#!/bin/sh
sudo systemctl start httpd
Apacheをインストールして起動するだけのなんとも単純なスクリプト
実行
[vagrant@vm1 ~]$ ansible 192.168.33.11 -k -m script -a 'httpd.sh'
scriptモジュールで指定したスクリプトをリモートに送り込んで実行できる
192.168.33.11 | SUCCESS => {
"changed": true,
"rc": 0,
"stderr": "",
"stdout": "読み込んだプラグイン:fastestmirror\r\nLoading mirror speeds from cached hostfile\r\n * base: ftp.riken.jp\r\n * extras: ftp.riken.jp\r\n * updates: ftp.riken.jp\r\n依存性の解決をしています\r\n--> トランザクションの確認を実行しています。\r\n---> パッケージ httpd.x86_64 0:2.4.6-40.el7.centos を インストール\r\n--> 依存性解決を終了しました。\r\n\r\n依存性を解決しました\r\n\r\n================================================================================\r\n Package アーキテクチャー\r\n バージョン リポジトリー 容量\r\n================================================================================\r\nインストール中:\r\n httpd x86_64 2.4.6-40.el7.centos base 2.7 M\r\n\r\nトランザクションの要約\r\n================================================================================\r\nインストール 1 パッケージ\r\n\r\n総ダウンロード容量: 2.7 M\r\nインストール容量: 9.4 M\r\nDownloading packages:\r\n\rhttpd-2.4.6-40.el7.centos. 21% [=== ] 0.0 B/s | 593 kB --:-- ETA \r\rhttpd-2.4.6-40.el7.centos. 23% [===- ] 62 kB/s | 645 kB 00:34 ETA \r\rhttpd-2.4.6-40.el7.centos. 38% [====== ] 139 kB/s | 1.0 MB 00:12 ETA \r\rhttpd-2.4.6-40.el7.centos. 50% [======== ] 192 kB/s | 1.4 MB 00:07 ETA \r\rhttpd-2.4.6-40.el7.centos. 61% [=========- ] 243 kB/s | 1.7 MB 00:04 ETA \r\rhttpd-2.4.6-40.el7.centos. 84% [============= ] 350 kB/s | 2.3 MB 00:01 ETA \r\rhttpd-2.4.6-40.el7.centos.x86_64.rpm | 2.7 MB 00:02 \r\nRunning transaction check\r\nRunning transaction test\r\nTransaction test succeeded\r\nRunning transaction\r\n警告: RPMDB は yum 以外で変更されました。\r\n\r インストール中 : httpd-2.4.6-40.el7.cen [ ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [# ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [## ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [#### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [##### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [###### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [####### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [######## ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [######### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [########## ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [########### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [############ ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [############# ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [############## ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [############### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [################ ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [################# ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [################## ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [################### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [#################### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.cen [##################### ] 1/1\r インストール中 : httpd-2.4.6-40.el7.centos.x86_64 1/1 \r\n\r 検証中 : httpd-2.4.6-40.el7.centos.x86_64 1/1 \r\n\r\nインストール:\r\n httpd.x86_64 0:2.4.6-40.el7.centos \r\n\r\n完了しました!\r\n",
"stdout_lines": [
"読み込んだプラグイン:fastestmirror",
"Loading mirror speeds from cached hostfile",
" * base: ftp.riken.jp",
" * extras: ftp.riken.jp",
" * updates: ftp.riken.jp",
"依存性の解決をしています",
"--> トランザクションの確認を実行しています。",
"---> パッケージ httpd.x86_64 0:2.4.6-40.el7.centos を インストール",
"--> 依存性解決を終了しました。",
"",
"依存性を解決しました",
"",
"================================================================================",
" Package アーキテクチャー",
" バージョン リポジトリー 容量",
"================================================================================",
"インストール中:",
" httpd x86_64 2.4.6-40.el7.centos base 2.7 M",
"",
"トランザクションの要約",
"================================================================================",
"インストール 1 パッケージ",
"",
"総ダウンロード容量: 2.7 M",
"インストール容量: 9.4 M",
"Downloading packages:",
"",
"httpd-2.4.6-40.el7.centos. 21% [=== ] 0.0 B/s | 593 kB --:-- ETA ",
"",
"httpd-2.4.6-40.el7.centos. 23% [===- ] 62 kB/s | 645 kB 00:34 ETA ",
"",
"httpd-2.4.6-40.el7.centos. 38% [====== ] 139 kB/s | 1.0 MB 00:12 ETA ",
"",
"httpd-2.4.6-40.el7.centos. 50% [======== ] 192 kB/s | 1.4 MB 00:07 ETA ",
"",
"httpd-2.4.6-40.el7.centos. 61% [=========- ] 243 kB/s | 1.7 MB 00:04 ETA ",
"",
"httpd-2.4.6-40.el7.centos. 84% [============= ] 350 kB/s | 2.3 MB 00:01 ETA ",
"",
"httpd-2.4.6-40.el7.centos.x86_64.rpm | 2.7 MB 00:02 ",
"Running transaction check",
"Running transaction test",
"Transaction test succeeded",
"Running transaction",
"警告: RPMDB は yum 以外で変更されました。",
"",
" インストール中 : httpd-2.4.6-40.el7.cen [ ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [# ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [## ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [#### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [##### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [###### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [####### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [######## ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [######### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [########## ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [########### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [############ ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [############# ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [############## ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [############### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [################ ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [################# ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [################## ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [################### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [#################### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.cen [##################### ] 1/1",
" インストール中 : httpd-2.4.6-40.el7.centos.x86_64 1/1 ",
"",
" 検証中 : httpd-2.4.6-40.el7.centos.x86_64 1/1 ",
"",
"インストール:",
" httpd.x86_64 0:2.4.6-40.el7.centos ",
"",
"完了しました!"
]
}
うまくいった模様。yumの結果は/dev/nullに落としておけばよかった
[vagrant@vm1 ~]$ curl http://192.168.33.11
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
(略)
Apacheが立ち上がった!
AnsibleのPlaybookを作ってみる
Ansibleで実行するコマンドをまとめたものをPlaybookというらしい。
Apacheをインストールして立ち上げるPlaybookを作って実行してみる。
Playbook作成
このへんを参考に
YAML形式のPlaybookを書いてみる
- hosts: 192.168.33.11
user: vagrant
tasks:
- name: install httpd
yum: pkg=httpd state=installed
notify:
- start httpd
handlers:
- name: start httpd
service: name=httpd state=started
こんな感じで
tasks: 1つのtaskにつき1モジュールを実行する
notify: task実行後に、指定した名前のhandlerを実行する
handlers: 1つのhandlerにつき1モジュールを実行する
Playbook実行
[vagrant@vm1 ~]$ ansible-playbook httpd.yml -k
PLAY ***************************************************************************
TASK [setup] *******************************************************************
ok: [192.168.33.11]
TASK [install httpd] ***********************************************************
changed: [192.168.33.11]
RUNNING HANDLER [start httpd] **************************************************
changed: [192.168.33.11]
PLAY RECAP *********************************************************************
192.168.33.11 : ok=3 changed=2 unreachable=0 failed=0
実行されたらしい
[vagrant@vm1 ~]$ curl http://192.168.33.11
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
(略)
Apacheが起動してる!
CentOS 7にAnsibleを導入
Vagrantで立てたCentOS 7の仮想マシン間で設定を自動化するため、Ansibleを導入してみる。
Ansibleのメリット
環境
マシン名: vm1
OS: CentOS 7
IPアドレス: 192.168.33.10
用途: Ansibleサーバ
マシン名: vm2
OS: CentOS 7
IPアドレス: 192.168.33.11
用途: Ansibleクライアント
サーバ設定
インストール
CentOS 7のリポジトリにAnsibleは入っていないので、まずはEPELを使えるようにする
[root@vm1 vagrant]# yum install epel-release
そしてAnsibleをインストール
[root@vm1 vagrant]# yum install ansible
インストール完了後、バージョンを確認してみる
[root@vm1 vagrant]# ansible --version
ansible 2.0.1.0
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
動いた
hostsファイル編集
Ansibleの操作対象サーバをhostsファイルに登録する必要がある
[vagrant@vm1 .ssh]$ vi /etc/ansible/hosts
vm2のIPアドレスを登録。webserversというグループ名にしておく
[webservers]
192.168.33.11
サンプルモジュール実行
[vagrant@vm1 ~]$ ansible 192.168.33.11 -m ping -k
192.168.33.11 | SUCCESS => {
"changed": false,
"ping": "pong"
}
-m モジュール名: 指定したモジュールを実行
-k: パスワード認証時にパスワード入力を求める
無事実行された
任意のコマンドを実行
[vagrant@vm1 ~]$ ansible 192.168.33.11 -k -a 'uname -a'
192.168.33.11 | SUCCESS | rc=0 >>
Linux vm2.localdomain 3.10.0-327.13.1.el7.x86_64 #1 SMP Thu Mar 31 16:04:38 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
-a 'ほげほげ': モジュールの引数を指定。 モジュールを指定しない場合、記述したコマンドをそのまま実行
これも実行できた
参考
Vagrantコマンドメモ
Vagrantのよく使うコマンド
基本操作
起動
$ vagrant up
停止
$ vagrant halt
ログイン
構築周り
Boxのダウンロード
$ vagrant box add Box名
ダウンロード済Boxの確認
$ vagrant box list
centos/7 (virtualbox, 1603.01)
仮想マシンの作成
$ vagrant init Box名
仮想マシン操作
仮想マシンの状態表示
$ vagrant status
Current machine states:
default running (virtualbox)
仮想マシンのssh情報
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile "/Users/tejitejt/vagrant/vm1/.vagrant/machines/default/virtualbox/private_key"
IdentitiesOnly yes
LogLevel FATAL
全仮想マシンの情報表示
$ vagrant global-status
id name provider state directory
------------------------------------------------------------------------
de2a00f default virtualbox running /Users/tejitejt/vagrant/vm1
仮想マシンの削除
$ vagrant destroy
Vagrantで立てたCentOS 7環境の設定
VagrantのBoxからCentOS 7を立ち上げただけじゃホストOSからsshすらできないので、そのへんの設定までやる
Vagrantfileの編集
$ cd ~/vagrant/vm1/
$ vi Vagrantfile
config.vm.network "private_network", ip: "192.168.33.10"
このへんのコメントアウトを外してローカルIPを有効にする
起動&ログイン
$ vagrant up
IPアドレス確認
(略)
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 08:00:27:a0:6d:aa brd ff:ff:ff:ff:ff:ff
inet 192.168.33.10/24 brd 192.168.33.255 scope global eth1
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fea0:6daa/64 scope link
valid_lft forever preferred_lft forever
ローカルIPがついた
rootになる
パスワード: vagrant
su: 認証失敗
vagrantの初期パスワードはvagrant、って各所に書いてあったのに失敗。なぜ?
これでいけた。やり方変わったのか?とりあえずrootになれたからOK
[root@localhost vagrant]# passwd
お好みのパスワードに変更
さっそくyumアップデート
[root@localhost vagrant]# yum update
ホスト名変えておこう
[root@localhost ~]# vi /etc/hostname
vm1.localdomain
再起動後に有効になる
おなじみのSELinuxオフ
[root@localhost vagrant]# getenforce
Enforcing
当然オンになっているので
[root@localhost vagrant]# setenforce 0
[root@localhost vagrant]# getenforce
Permissive
一時的に無効化して
[root@localhost vagrant]# vi /etc/selinux/config
恒久対処
SELINUX=enforcing
↓
SELINUX=disabled
設定変更
[root@localhost vagrant]# /sbin/shutdown -r now
再起動して
[vagrant@vm1 ~]$ getenforce
Disabled
無効になった
firewalld確認
[vagrant@vm1 ~]$ su
[root@localhost vagrant]# systemctl is-enabled firewalld
disabled
デフォルトで無効らしい
Mac側からssh
vagrant@192.168.33.10's password: vagrant
[vagrant@vm1 ~]$
ログインできた〜
VagrantでCentOS 7を立ち上げる
OSイメージの入手から、起動して終了してみるまで
boxの追加
ここで仮想マシンのテンプレートを探す
Discover Vagrant Boxes | Atlas by HashiCorp
CentOS 7のboxをダウンロード
==> box: Loading metadata for box 'centos/7'
box: URL: https://atlas.hashicorp.com/centos/7
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.
1) libvirt
2) virtualbox
Enter your choice: 2
==> box: Adding box 'centos/7' (v1603.01) for provider: virtualbox
box: Downloading: https://atlas.hashicorp.com/centos/boxes/7/versions/1603.01/providers/virtualbox.box
==> box: Successfully added box 'centos/7' (v1603.01) for 'virtualbox'!
$ vagrant box list
centos/7 (virtualbox, 1603.01)
ダウンロードされた
Vagrant初期設定
仮想マシンごとにディレクトリを作成して初期化
$ cd ~
$ mkdir -p vagrant/vm1
$ cd vagrant/vm1
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
仮想マシン起動
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos/7'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'centos/7' is up to date...
==> default: Setting the name of the VM: vm1_default_1461916092013_42692
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Remote connection disconnect. Retrying...
default: Warning: Remote connection disconnect. Retrying...
default: Warning: Remote connection disconnect. Retrying...
default: Warning: Remote connection disconnect. Retrying...
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
default: No guest additions were detected on the base box for this VM! Guest
default: additions are required for forwarded ports, shared folders, host only
default: networking, and more. If SSH fails on this machine, please install
default: the guest additions and repackage the box to continue.
default:
default: This is not an error message; everything may continue to work properly,
default: in which case you may ignore this message.
==> default: Rsyncing folder: /Users/tejitejt/vm1/ => /home/vagrant/sync
起動したっぽい
仮想マシンにssh
プロンプトが変わった
[vagrant@localhost ~]$ cat /etc/redhat-release
CentOS Linux release 7.2.1511 (Core)
きた〜
仮想マシンを抜ける
Connection to 127.0.0.1 closed.
仮想マシンを落とす
$ vagrant halt
==> default: Attempting graceful shutdown of VM...
参考