LoginSignup
7
9

More than 5 years have passed since last update.

AnsibleでVPSにLAMP環境を自動構築

Posted at

前回ではAnsibleとvagrantでローカル環境構築の方法を記載しましたが、
今回はVPSでのLAMP環境の構築の自動化をやってみました。

今回の開発環境と手順は
ローカル環境(MAC)からServerMan@VPS上にLAMP環境の自動構築の方法になります。
もちろんVPS側にAnsibleをインストールして自動構築の方法もありますが
今回は前者の方法でのご説明をします。

事前準備
■vpsにssh接続が可能になっていること
■ローカル環境ににAnsibleのインストール済であること

ansibleを作業ディレクトリとします
/Users/example/ansible

inventryfileファイルの作成
今回はhostsというファイル名で作成

[web]
2x.1xx.9x.xxx:sshポート番号 ansible_ssh_private_key_file=~/.ssh/id_rsa

VPSに公開鍵認証を使用している場合は鍵を指定します。

playbookの作成
今回はplaybook.ymlというファイル名で作成

---
 - hosts: web
   user: VPSのユーザー名
   sudo: yes
   tasks:
    - yum: name=vim state=latest
    - name: install apache
      yum: name=httpd state=present
    - name: start apache and enabled
      service: name=httpd state=started enabled=yes
    - name: set epel repository
      shell: rpm -Uvh --force http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
    - name: set remi repository
      command: sudo rpm -Uvh --force http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
    - name: install php packages
      yum: name={{item}} enablerepo=remi,epel state=present
      with_items:
       - php
       - php-pear
       - php-devel
       - php-mbstring
       - php-pdo
       - php-mysql
       - php-gd
       - php-xdebug
      notify:
       - restart apache
    - name: install mysql
      yum: name={{ item }} enablerepo=remi,epel state=installed
      with_items:
       - mysql-server
       - MySQL-python
      notify:
        - start mysql
   handlers:
    - name: restart apache
      service: name=httpd state=restarted enabled=yes #enabled=yes 自動起動
    - name: start mysql
      service: name=mysqld state=started enabled=yes
    - name: mysql set password
      command: mysqladmin -u root password "{{ mysql_root_pw }}" #passwordの設定

流れとしては
vimのインストール
apacheのインストール
phpのインストール
mysqlのインストール
mysqlのユーザーのパスワード設定

となっています。

ではローカル環境からAnsibleでVPSに接続可能かどうかのチェックをしてみます。
ansibleディレクトリ上で

ansible -m ping web -i hosts -u ユーザー名

ユーザー名はVPSのユーザー名となります。
rootユーザーでのログインを禁止している場合はrootでログインできないので注意です。

2x.1xx.9x.xxx | success >> {
    "changed": false,
    "ping": "pong"
}

上記のようなレスポンスが返ってきたら接続は成功です。

それではいよいよ自動構築します。

ansible-playbook -i hosts -vv  playbook.yml -u ユーザー名 --ask-sudo-pass

ssh接続のパスワードを入力する必要がありますので入力したらあとはAnsibleさんがすべてやってくれます。

......略
2x.1xx.9x.xxx              : ok=8    changed=2    unreachable=0    failed=0

こんな感じにunreachable=0ならとりあえず成功してます。

7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9