ansible-playbookでvagrantからEC2にデプロイする方法

[EC2側]
まず、EC2を起動し、ターミナルからssh接続
$ ssh ec2-user@**** -i ~/.ssh/***.pem
$ cd /home/release
$ ls
LICENSE appspec.yml index.html scripts

[vagrant側]
.ssh/、inventory/hostsを作成済み
/hosts

[targets]
**.***.**.**

今回デプロイするtest.htmlを作成する

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	ansible deploy test
</body>
</html>

$ ls
LICENSE appspec.yml index.html inventory playbook.yml scripts test.html

playbook.yml

- hosts: targets
  sudo: yes
  tasks:
    - name: put test.html
      copy: src=test.html dest=/home/release/ owner=root group=root mode=640

### デプロイ実行
$ ansible-playbook -i inventory/hosts –private-key=.ssh/***.pem playbook.yml -u ec2-user
PLAY [targets] *****************************************************************

TASK [Gathering Facts] *********************************************************
ok: [**.***.**.**]

TASK [put test.html] ***********************************************************
changed: [**.***.**.**]

PLAY RECAP *********************************************************************
**.***.**.** : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

### EC2側で確認
$ ls
LICENSE appspec.yml index.html scripts test.html
$ sudo cat test.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	ansible deploy test
</body>
</html>

playbook.ymlは、デプロイする場合は、copy: src=${source file} dest=${dest directory} owner=root group=root mode=640 でOK
test.htmlを修正して、再度ansible-playbookを叩いた場合でも、EC2側で反映されていることが確認できます。

ansibleでvagrantからEC2にSSH接続するテスト

Githubではなく、ローカルからEC2にデプロイしたい時もあるでしょう。
という事で、AnsibleからEC2にSSH接続する方法を確認していきます。

### 前提
– vagrantにansibleインストール済

$ ansible –version
ansible 2.8.5

### .gitignore
git pushする際に、秘密鍵がレポジトリにpushされないよう、gitignoreを設定します。
.gitignore

/.ssh

.ssh フォルダにテストファイルを作成して.gitignoreが動くかテスト
$ git add .
$ git commit -m “gitignore added”
$ git push -u origin master

レポジトリにて、.sshがpushされていない事を確認

## -m pingテスト
### .ssh
ec2の秘密鍵を.sshに配置
$ chmod 700 .ssh/

### EC2
instanceからEC2をstart

### host
inventory/hosts
-> instanceのpublic ip(テスト用)を入れる

[targets]
**.***.**.**

### ansible command
$ ansible all -i inventory/hosts -m ping

**.***.**.** | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '**.***.**.**' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic).", 
    "unreachable": true
}

鍵認証が上手くいっていない。

$ ansible all -i inventory/hosts –private-key=.ssh/***.pem -m ping -u ec2-user

**.***.**.** | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

httpd24-tools conflicts with httpd-tools-2.2.34-1.15.amzn1.x86_64

playbook.ymlでyum installを書きます。

---
- hosts: all
  sudo: yes
  tasks:
    - name: Install a list of packages
      yum:
        name:
          - httpd24
          - php71
	  - mysql56-server
          - php71-mysqlnd
        state: present
    - name: start apache and enabled
      service: name=httpd state=started enabled=yes

fatal: [192.168.33.10]: FAILED! => {“changed”: false, “msg”: “Error: httpd24-tools conflicts with httpd-tools-2.2.34-1.15.amzn1.x86_64\n”, “rc”: 1, “results”: [“Loaded plugins: priorities, update-motd, upgrade-helper\nResolving Dependencies\n–> Running transaction check\n—> Package httpd24.x86_64 0:2.4.27-3.73.amzn1 will be installed\n–> Processing Dependency: httpd24-tools = 2.4.27-3.73.amzn1 for package: httpd24-2.4.27-3.73.amzn1.x86_64\n—> Package mysql56-server.x86_64 0:5.6.37-1.26.amzn1 will be installed\n–> Processing Dependency: mysql56-common(x86-64) = 5.6.37-1.26.amzn1 for package: mysql56-server-5.6.37-1.26.amzn1.x86_64\n–> Processing Dependency: mysql56-errmsg(x86-64) = 5.6.37-1.26.amzn1 for package: mysql56-server-5.6.37-1.26.amzn1.x86_64\n–> ….

httpd24とhttpd-tools-2.2.34がconflictとなっているようです。
勘違いしていたのが、php71を入れると、httpdがインストールされるので、httpd24は削除します。

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.33.10]

TASK [Install a list of packages] **********************************************
ok: [192.168.33.10]

TASK [start apache and enabled] ************************************************
changed: [192.168.33.10]

PLAY RECAP *********************************************************************
192.168.33.10 : ok=3 changed=1 unreachable=0 failed=0

OK!
ただ、playbook.ymlがどんどん増えていくんだが、これでいいのか?

yum installをansibleにまとめたい

ドキュメントに書いても良いが、やはりansibleでまとめたい。

hosts

192.168.33.10

ansible.cnf

[defaults]
hostfile =./hosts

playbook.yml

---
- hosts: all
  sudo: yes
  tasks:
    - name: install apache
      yum: name=httpd state=latest
    - name: start apache and enabled
      service: name=httpd state=started enabled=yes

[vagrant@localhost ansible]$ ansible-playbook playbook.yml –connection=local
[DEPRECATION WARNING]: [defaults]hostfile option, The key is misleading as it
can also be a list of hosts, a directory or a list of paths , use [defaults]
inventory=/path/to/file|dir instead. This feature will be removed in version
2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False
in ansible.cfg.
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
make sure become_method is ‘sudo’ (default). This feature will be removed in
version 2.6. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.33.10]

TASK [install apache] **********************************************************
changed: [192.168.33.10]

TASK [start apache and enabled] ************************************************
changed: [192.168.33.10]

PLAY RECAP *********************************************************************
192.168.33.10 : ok=3 changed=2 unreachable=0 failed=0

ansibleのyum moduleのページを見てみましょう。
https://docs.ansible.com/ansible/latest/modules/yum_module.html#yum-module

- name: Install a list of packages
  yum:
    name:
      - nginx
      - postgresql
      - postgresql-server
    state: present

なるほど、これで、middlewareを追加していけば良いのかな。

さくら共有サーバーにansibleで命令

以下のように書く
-e ‘ansible_python_interpreter=/usr/local/bin/python’

インベントリファイルにip, username, passを書くと、

# ansible all -i hosts -m ping -e 'ansible_python_interpreter=/usr/local/bin/python'
xx.xxx.xxx.xxx | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
xx.xxx.xxx.xxx | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

うおおおおおおおおおおおおおおおおおおおおおおおおおおお
まじかーーーーーーーーーーーーーーーーー

ansible.cfg

[defaults]
hostfile = ./hosts

# ansible all -m ping -e ‘ansible_python_interpreter=/usr/local/bin/python’
[DEPRECATION WARNING]: [defaults]hostfile option, The key is misleading as it
can also be a list of hosts, a directory or a list of paths , use [defaults]
inventory=/path/to/file|dir instead. This feature will be removed in version
2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False
in ansible.cfg.
xx.xxx.xxx.xxx | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
xx.xxx.xxx.xxx | SUCCESS => {
“changed”: false,
“ping”: “pong”
}

インベントリファイルにuser passを書いていく

[sakura1]

[sakura2]

[sakura1:vars]
ansible_ssh_port=22
ansible_ssh_user=
ansible_ssh_pass=
ansible_sudo_pass=

[sakura2:vars]
ansible_ssh_port=22
ansible_ssh_user=
ansible_ssh_pass=
ansible_sudo_pass=

[root@ ansible]# ansible all -i hosts -m ping
| FAILED! => {
“changed”: false,
“module_stderr”: “Shared connection to xxx.xx.xx.xx closed.\r\n”,
“module_stdout”: “/usr/bin/python: not found\r\n”,
“msg”: “MODULE FAILURE”,
“rc”: 127
}
xx.xxx.xxx.xx | FAILED! => {
“changed”: false,
“module_stderr”: “Shared connection to xx.xxx.xxx.xx closed.\r\n”,
“module_stdout”: “/usr/bin/python: not found\r\n”,
“msg”: “MODULE FAILURE”,
“rc”: 127
}

ん? python2.7が入っていない?
[root@localhost ~]# yum -y install centos-release-scl-rh
[root@localhost ~]# yum -y install python27

[root@ ansible]# scl enable python27 bash
[root@ ansible]# python –version
Python 2.7.13

ansible all -i hosts -m ping -e ‘ansible_python_interpreter=/opt/rh/python27/root/usr/bin/python2.7’

アアアアアアアアアアアアア、
remote hostにはいっていないとか。。

Ansibleの設定を加えていこう

var/local/ansible
vi .ssh/config

Host sakura1
  HostName 182.xx.xx.xx
Host sakura2
  HostName 49.xxx.xxx.xxx

公開鍵を作成する
# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /var/local/ansible/.ssh/id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /var/local/ansible/.ssh/id_rsa.
Your public key has been saved in /var/local/ansible/.ssh/id_rsa.pub.
The key fingerprint is:
c8:43:16:c5:69:5e:ad:d9:bb:0c:0e:22:7e:06:9a:46 root@hoge.vs.sakura.ne.jp
The key’s randomart image is:
+–[ RSA 2048]—-+
| .o.. . |
| .+ . . |
| oo . + |
| + .. o . |
| + S . |
| E o … . . |
| . + o . o o . |
| + . o . o |
| . o |
+—————–+

# ssh-copy-id sakura1
あれ? なんかうまくいかない。

# ansible all -i hosts -m ping
The authenticity of host ‘hoge’ can’t be established.
RSA key fingerprint is 0c:3.
Are you sure you want to continue connecting (yes/no)? The authenticity of host ‘1hoge)’ can’t be established.
RSA key fingerprint is 1f:3c:fa.
Are you sure you want to continue connecting (yes/no)? yes
hoge | UNREACHABLE! => {
“changed”: false,
“msg”: “Failed to connect to the host via ssh: Warning: Permanently added ‘hoge’ (RSA) to the list of known hosts.\r\nPermission denied (publickey,password).\r\n”,
“unreachable”: true
}

Please type ‘yes’ or ‘no’: yes
hoge | UNREACHABLE! => {
“changed”: false,
“msg”: “Failed to connect to the host via ssh: Warning: Permanently added ‘1hoge’ (RSA) to the list of known hosts.\r\nPermission denied (publickey,password).\r\n”,
“unreachable”: true
}

やはりRSA接続が上手くいっていない
インベントリファイルにパスワードを書く方法を模索か

vpsでansibleを動かす準備をしよう

1.さくら共有サーバー2つ分のipアドレスを取得
2.vpsにanshibleをインストール
3.vpsからさくら共有サーバーにping ponコマンドを実行し、ansibleが動くことを確認
4.vpsからファイルを転送して、アクセスする

まずはここまでやりたい。1は終了。
ansibleのplaybookをどこで実行するか?var/wwwwはapacheが動いているので、/var/localにansibleフォルダを作るのが無難か。

ansibleをインストールします。
# sudo yum -y install ansible

ansibleが入りました。config fileはetcに入ってますね。いいのか?
[root@hoge ansible]# ansible –version
ansible 2.6.4
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/root/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.6/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]

ansibleでmysqld

---
- hosts: all
  sudo: yes
  tasks:
    - name: add a new user
      user: name=hpscript

- hosts: web
  sudo: yes
  tasks:
    - name: install apache
      yum: name=httpd state=latest
    - name: start apache and enabled
      service: name=httpd state=started enabled=yes
    - name: change owner
      file: dest=/var/www/html owner=vagrant recurse=yes
    - name: copy zabbix.php
      copy: src=./zabbix.php dest=/var/www/html/zabbix.php owner=vagrant
  #   - name: install php packages
  #     yum: name={{item}} state=latest
  #     with_items:
  #       - php
  #       - php-dev
  #       - php-mbstring
  #       - php-mysql
  #     notify:
  #       - restart apache
  # handlers: 
    - name: restart apache
      service: name=httpd state=restarted

- hosts: db
  sudo: yes
  tasks:
    - name: install mysql
      yum: name={{item}} state=latest
      with_items:
        - mysql-server
        - MySQL-python
    - name: start mysql and enabled
      service: name=mysqld state=started enabled=yes
    # - name: create a database
    #   mysql_db: name=mydb state=prsent

[vagrant@host ~]$ ansible-playbook pbook.yml
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
make sure become_method is ‘sudo’ (default).
This feature will be removed in a
future release. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [192.168.43.53]
ok: [192.168.43.52]

TASK [add a new user] **********************************************************
ok: [192.168.43.52]
ok: [192.168.43.53]

PLAY [web] *********************************************************************

TASK [setup] *******************************************************************
ok: [192.168.43.52]

TASK [install apache] **********************************************************
ok: [192.168.43.52]

TASK [start apache and enabled] ************************************************
ok: [192.168.43.52]

TASK [change owner] ************************************************************
ok: [192.168.43.52]

TASK [copy zabbix.php] *********************************************************
ok: [192.168.43.52]

TASK [restart apache] **********************************************************
changed: [192.168.43.52]

PLAY [db] **********************************************************************

TASK [setup] *******************************************************************
ok: [192.168.43.53]

TASK [install mysql] ***********************************************************
ok: [192.168.43.53] => (item=[u’mysql-server’, u’MySQL-python’])

TASK [start mysql and enabled] *************************************************
ok: [192.168.43.53]

PLAY RECAP *********************************************************************
192.168.43.52 : ok=8 changed=1 unreachable=0 failed=0
192.168.43.53 : ok=5 changed=0 unreachable=0 failed=0

ok
さくらvpsにansibleを入れて、共有サーバーにコマンドを実行していきたい。
まず、ssh接続するために、ipアドレスからか。