2018年8月3日金曜日

VagrantでAnsibleをインストールした仮想マシン(Debian Stretch/9.4)を構築する

Ansibleはオープンソースの構成管理ツールで、ソフトウェアのインストール等を自動化できます。

〇構築方法
以下のVagrantfileを使用して、Ansibleをインストールした仮想マシン(Debian Stretch/9.4)を構築できます。

Vagrantfile
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "bento/debian-9.4"
  config.vm.hostname = "db94ansible"
  config.vm.provider :virtualbox do |vbox|
     vbox.name = "db94ansible"
     vbox.cpus = 2
     vbox.memory = 2048
     vbox.customize ["modifyvm", :id, "--nicpromisc2","allow-all"]
  end
config.vm.network "private_network", ip: "192.168.55.105", :netmask => "255.255.255.0"
config.vm.network "public_network", ip:"192.168.1.105", :netmask => "255.255.255.0"
  config.vm.provision "shell", inline: <<-SHELL
# update packages
apt-get update
#DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade
locale-gen ja_JP.UTF-8
localectl set-locale LANG=ja_JP.UTF-8

# install ansible
echo "deb http://ppa.launchpad.net/ansible/ansible/ubuntu stretch main" >> /etc/apt/sources.list
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 93C4A3FD7BB9C367
apt-get update
apt-get -y install ansible sshpass

SHELL
end


○関連情報
・Ansibleに関する他の記事はこちらを参照してください。

VagrantでSwirl/Docker/Docker Composeがインストールされた仮想マシン(Debian Stretch/9.4)を構築する

Swirlを使用してブラウザからDockerを管理することができます。

〇Swirlの画面


〇構築方法
1.以下のVagrantfileを使用して、Swirl/Docker/Docker Composeがインストールされた仮想マシン(Debian Stretch/9.4)を構築します。

Vagrantfile
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "bento/debian-9.4"
  config.vm.hostname = "db94swirl"
  config.vm.provider :virtualbox do |vbox|
     vbox.name = "db94swirl"
     vbox.cpus = 4
     vbox.memory = 4096
     vbox.customize ["modifyvm", :id, "--nicpromisc2","allow-all"]
  end
config.vm.network "private_network", ip: "192.168.55.118", :netmask => "255.255.255.0"
config.vm.network "public_network", ip:"192.168.1.118", :netmask => "255.255.255.0"
  config.vm.provision "shell", inline: <<-SHELL
# update packages
apt-get update
#DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade
locale-gen ja_JP.UTF-8
localectl set-locale LANG=ja_JP.UTF-8

# install docker-ce
apt-get -y install apt-transport-https ca-certificates curl gnupg2 software-properties-common
curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | sudo apt-key add -
apt-key fingerprint 0EBFCD88
add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo "$ID") \
   $(lsb_release -cs) \
   stable"
apt-get update
apt-get -y install docker-ce

groupadd docker
adduser vagrant docker
systemctl enable docker
docker version

# install docker compose
curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
docker-compose --version

# initizalize swarm
docker swarm init --advertise-addr 192.168.55.118  | grep -e '--token' | sed -e 's/    //' - > /vagrant/joincmd.sh

# install swirl
cat << EOF > docker-compose.yml
version: '3'

services:
  swirl:
    image: cuigh/swirl
    environment:
      DB_ADDRESS: mongodb:27017/swirl
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - 8001:8001
    deploy:
      replicas: 1
      placement:
        constraints: [node.role == manager]
    depends_on:
      - mongodb
  mongodb:
    image: mongo:3.7-jessie
    container_name: "mongodb"
    volumes:
      - "mongodb-data:/data/db"
      - "mongodb-configdb:/data/configdb"
    ports:
      - 27017:27017
volumes:
  mongodb-data:
    driver: local
  mongodb-configdb:
    driver: local
EOF
docker-compose up -d

SHELL
end

2.ブラウザからhttp://192.168.55.118:8001にアクセスして、管理者情報を入力します。


○関連情報
・Swirlに関する他の記事はこちらを参照してください。

2018年8月2日木曜日

AnsibleでPrometheus Node Exporterをインストールする(Debian Stretch/9.4, Ubuntu16.04, Ubuntu18.04)

Prometheus Node Exporterでハードウェア、OS情報の収集を行います。

〇インストール方法
1.下準備
~/.ansible.cfgに以下の内容を設定します
[ssh_connection]
pipelining=True
[defaults]
host_key_checking = False

2. インストール対象ホストのユーザやパスワードを環境に合わせてinventoryファイルに記入します

inventory例
[node-exporter]
192.168.1.106

[all:vars]
ansible_ssh_port=22
ansible_ssh_user=vagrant
ansible_ssh_pass=vagrant
ansible_sudo_pass=vagrant

3.inventory node-exporter-deb.ymlを準備し、以下のコマンドを実行します。
ansible-playbook -i inventory node-exporter-deb.yml

node-exporter-deb.yml
- hosts: node-exporter
  vars:
    - password: prometheus
  tasks:
    - name: create prometheus group
      group:
        name: prometheus
      become: true
    - name: create prometheus user
      user:
        name: prometheus
        group: prometheus
        password: "{{ password | password_hash('sha512') }}"
      become: true
    - name: create prometheus directory
      file:
        path: /opt/prometheus
        state: directory
        owner: prometheus
      become: true
    - name: download prometheus node exporter
      get_url:
        url: https://github.com/prometheus/node_exporter/releases/download/v0.16.0/node_exporter-0.16.0.linux-amd64.tar.gz
        dest: /opt/prometheus/
      become: true
      become_user: prometheus
    - name: extract prometheus node exporter
      unarchive:
        remote_src: yes
        src: /opt/prometheus/node_exporter-0.16.0.linux-amd64.tar.gz
        dest: /opt/prometheus/
      become: true
      become_user: prometheus
    - name: symlink
      file:
        path: /bin/node_exporter
        state: link
        src: /opt/prometheus/node_exporter-0.16.0.linux-amd64/node_exporter
      become: true
    - name: clean up
      file:
        state: absent
        path: /opt/prometheus/node_exporter-0.16.0.linux-amd64.tar.gz
      become: yes
      become_user: prometheus
    - name: setup systemd
      blockinfile:
        dest: /etc/systemd/system/node-exporter.service
        create: yes
        block: |
          [Unit]
          Description=Prometheus Node Exporter
          Requires=network.target
          [Service]
          Restart=always
          WorkingDirectory=/opt/prometheus/node_exporter-0.16.0.linux-amd64
          ExecStart=/bin/node_exporter
          ExecReload=/bin/kill -HUP $MAINPID
          [Install]
          WantedBy=multi-user.target
      become: true
    - name: enable and start node-exporter
      systemd:
        daemon_reload: yes
        enabled: yes
        state: started
        name: node-exporter.service
      become: true

VagrantでZabbixとPostgreSQLをインストールした仮想マシン(Debian Stretch/9.4)を構築する

Zabbixはサーバー監視ソフトウェアです。

〇Zabbixの画面

ユーザ名、パスワードはAdmin/zabbixです。

〇構築方法
1. 以下のVagrantfileを使用して、ZabbixとPostgreSQLをインストールした仮想マシン(Debian Stretch/9.4)を構築します。

Vagrantfile
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "bento/debian-9.4"
  config.vm.hostname = "db94zabbixpg"
  config.vm.provider :virtualbox do |vbox|
     vbox.name = "db94zabbixpg"
     vbox.cpus = 2
     vbox.memory = 2048
     vbox.customize ["modifyvm", :id, "--nicpromisc2","allow-all"]
  end
config.vm.network "private_network", ip: "192.168.55.108", :netmask => "255.255.255.0"
config.vm.network "public_network", ip:"192.168.1.108", :netmask => "255.255.255.0"
  config.vm.provision "shell", inline: <<-SHELL
apt-get -y install task-japanese
sed -i -e 's/# ja_JP.UTF-8 UTF-8/ja_JP.UTF-8 UTF-8/' /etc/locale.gen
locale-gen
update-locale LANG=ja_JP.UTF-8
localectl set-locale LANG=ja_JP.UTF-8
localectl set-keymap jp106
apt-get update
#DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade


# install postgresql
apt-get -y install postgresql-9.6
echo "listen_addresses='*'" >> /etc/postgresql/9.6/main/postgresql.conf

#sed -i 's/host.*all.*all.*127.0.0.1/#host    all             all             127.0.0.1/g' /etc/postgresql/9.6/main/pg_hba.conf

echo "host    all         all         127.0.0.1/32          password" >> /etc/postgresql/9.6/main/pg_hba.conf
echo "host    all         all         192.168.1.0/24          password" >> /etc/postgresql/9.6/main/pg_hba.conf
echo "host    all         all         192.168.55.0/24          password" >> /etc/postgresql/9.6/main/pg_hba.conf

su - postgres << EOF
createdb -T template0 --locale=ja_JP.UTF-8 --encoding=UTF8 zabbix
psql -c "
alter user postgres with password 'postgres';
create user zabbix with password 'zabbix';
grant all privileges on database zabbix to zabbix;
"
EOF
echo "postgres:postgres" | chpasswd
systemctl restart postgresql.service


# install zabbix
wget http://repo.zabbix.com/zabbix/3.4/debian/pool/main/z/zabbix-release/zabbix-release_3.4-1+stretch_all.deb
dpkg -i zabbix-release_3.4-1+stretch_all.deb
apt-get update
apt-get -y install zabbix-server-pgsql zabbix-frontend-php php-pgsql zabbix-agent snmp
export PGPASSWORD=zabbix
zcat /usr/share/doc/zabbix-server-pgsql*/create.sql.gz | psql -h localhost -U zabbix zabbix
sed -i -e 's/# DBPassword=/DBPassword=zabbix/' /etc/zabbix/zabbix_server.conf
sed -i -e 's|# php_value date.timezone Europe/Riga|php_value date.timezone Asia/Tokyo|' /etc/apache2/conf-enabled/zabbix.conf

systemctl enable zabbix-server.service
systemctl start zabbix-server.service
systemctl enable zabbix-agent.service
systemctl start zabbix-agent.service
systemctl restart apache2.service

echo 'access to http://192.168.1.108/zabbix/'
echo 'user: Admin   password: zabbix'
SHELL
end

2.ブラウザからhttp://192.168.1.108/zabbix/にアクセスします。「Next Step」をクリックします。


3.「Next Step」をクリックします。


4.Passwordフィールドにzabbixを入力して、「Next Step」をクリックします。


5.「Next Step」をクリックします。


6.「Next Step」をクリックします。


7.「Finish」をクリックします。


2018年8月1日水曜日

VagrantでAtom、Xfceデスクトップ環境とXRDPがインストールされた仮想マシン(Ubuntu18.04)を構築する

Atomはオープンソースのテキストエディターです。

○Atomの画面


○構築方法
以下のVagrantfileを使用して、Atom、Xfceデスクトップ環境デスクトップ環境をインストールした仮想マシン(Ubuntu18.04)を構築する事ができます。
XRDPがインストールされているので、Windowsのリモートデスクトップで接続することができます。ユーザ名はvagrant、パスワードもvagrantでログオンできます。

Vagrantfile
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "bento/ubuntu-18.04"
  config.vm.hostname = "ub1804xfceatom"
config.vm.network :public_network, ip:"192.168.1.117"
config.vm.network "private_network", ip: "192.168.55.117", :netmask => "255.255.255.0"
  config.vm.provider :virtualbox do |vbox|
     vbox.name = "ub1804xfceatom"
     vbox.gui = true
     vbox.cpus = 2
     vbox.memory = 2048
     vbox.customize ["modifyvm", :id, "--nicpromisc2","allow-all"]
  end
  config.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get -y install language-pack-ja
sed -i.bak -e "s#http://archive.ubuntu.com/ubuntu/#http://ftp.riken.jp/pub/Linux/ubuntu/#g" /etc/apt/sources.list
localectl set-locale LANG=ja_JP.UTF-8
localectl set-keymap jp106
apt-get update
apt-get -y install xrdp=0.9.5-2 fcitx-mozc xubuntu-desktop language-pack-ja language-pack-ja
im-config -n fcitx

apt-get -y install --install-recommends linux-generic-hwe-18.04 xserver-xorg-hwe-18.04
apt-get -y install virtualbox-guest-dkms virtualbox-guest-utils virtualbox-guest-x11

sed -i -e "s/allowed_users=console/allowed_users=anybody/" /etc/X11/Xwrapper.config

echo "xfce4-session" > /home/vagrant/.xsession
apt-get -y purge light-locker

# install atom
apt-get -y install  gvfs-bin git xdg-utils
wget https://github.com/atom/atom/releases/download/v1.29.0/atom-amd64.deb
dpkg -i atom-amd64.deb

init 5
SHELL
end


○関連情報
・Atomに関する他の記事はこちらを参照してください。

VagrantでApache AirflowとMySQLをインストールした仮想マシン(Debian Stretch/9.4)を構築する

Apache AirflowはPython言語のタスクスケジューラです。

〇Apache Airflowの画面


〇構築方法
1.以下のVagrantfileを使用して、 Apache Airflowをインストールした仮想マシン(Debian Stretch/9.4)を構築します。

Vagrantfile
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "bento/debian-9.4"
  config.vm.hostname = "db94airflow"
  config.vm.provider :virtualbox do |vbox|
     vbox.name = "db94airflow"
     vbox.cpus = 4
     vbox.memory = 4096
     vbox.customize ["modifyvm", :id, "--nicpromisc2","allow-all"]
  end
config.vm.network "private_network", ip: "192.168.55.115", :netmask => "255.255.255.0"
config.vm.network "public_network", ip:"192.168.1.115", :netmask => "255.255.255.0"
  config.vm.provision "shell", inline: <<-SHELL
apt-get -y install task-japanese
sed -i -e 's/# ja_JP.UTF-8 UTF-8/ja_JP.UTF-8 UTF-8/' /etc/locale.gen
locale-gen
update-locale LANG=ja_JP.UTF-8
localectl set-locale LANG=ja_JP.UTF-8
localectl set-keymap jp106
timedatectl set-timezone Asia/Tokyo
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade

# install mysql
wget https://dev.mysql.com/get/mysql-apt-config_0.8.9-1_all.deb
export DEBIAN_FRONTEND=noninteractive
echo mysql-apt-config mysql-apt-config/enable-repo select mysql-5.7-dmr | sudo debconf-set-selections
dpkg -i mysql-apt-config_0.8.9-1_all.deb
apt-get update
apt-get -y install mysql-server
mysql -uroot -e "CREATE DATABASE airflow DEFAULT CHARACTER SET utf8;"
mysql -uroot -e "CREATE USER airflow@localhost IDENTIFIED BY 'airflow';"
mysql -uroot -e "GRANT ALL PRIVILEGES ON airflow.* TO 'airflow'@'localhost';"
mysql -uroot -e "FLUSH PRIVILEGES;"
apt-get -y install libmysqlclient-dev python3-dev build-essential
apt-get -y install redis-server

# install pipenv
apt-get -y install python3.5
apt-get -y install python-pip
#pip install --upgrade pip
pip install pip==9.0.1
pip install --upgrade setuptools
pip install pipenv


# install airflow.
groupadd airflow
useradd -g airflow -s /bin/bash -d /home/airflow -m airflow
mkdir -p /opt/airflow/dags
chown -R airflow:airflow /opt/airflow
sudo -u airflow /bin/bash << AF_EOF
export AIRFLOW_HOME=/opt/airflow
cd /opt/airflow
pipenv --python 3.5
pipenv install
pipenv run python -V
pipenv install redis
pipenv install apache-airflow[devel,mysql,celery,cryptography]==1.9.0


wget https://raw.githubusercontent.com/apache/incubator-airflow/master/airflow/config_templates/default_airflow.cfg
cp default_airflow.cfg airflow.cfg

sed -i -e 's#sql_alchemy_conn = sqlite:///\{AIRFLOW_HOME\}/airflow.db#sql_alchemy_conn = mysql://airflow:airflow@localhost:3306/airflow#'  airflow.cfg
sed -i -e 's/executor = SequentialExecutor/executor = CeleryExecutor/' airflow.cfg
sed -i -e 's#\{AIRFLOW_HOME\}#/opt/airflow#' airflow.cfg
sed -i -e 's#broker_url = sqla\+mysql://airflow:airflow@localhost:3306/airflow#broker_url = redis://localhost:6379#' airflow.cfg
sed -i -e 's#load_examples = True#load_examples = False#' airflow.cfg
sed -i -e 's#default_timezone = utc#default_timezone = Asia/Tokyo#' airflow.cfg

cat << EOF > gen.py
from cryptography.fernet import Fernet
fernet_key= Fernet.generate_key()
print(fernet_key.decode('utf-8'), end='"')
EOF
pipenv run python gen.py > /tmp/fernet_key
echo -n 'export FERNET_KEY="' > /tmp/setfernetkey
cat /tmp/fernet_key >> /tmp/setfernetkey
AF_EOF

source /tmp/setfernetkey
sed -i -e "s/{FERNET_KEY}/$FERNET_KEY/" /opt/airflow/airflow.cfg

sudo -u airflow /bin/bash << AF_EOF
export AIRFLOW_HOME=/opt/airflow
cd /opt/airflow
pipenv run airflow initdb

# prepare a sample dag
cat << EOF > /opt/airflow/dags/dag_example1.py
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

operator_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2018, 7, 1),
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

dag = DAG(
    dag_id='dag_example1',
    default_args=operator_args,
    catchup=False,
    schedule_interval='0,5,10,15,20,25,30,35,40,45,50,55 * * * *'
)

task1 = BashOperator(
    task_id='task1',
    bash_command='echo "task1:"`date` >> /tmp/test.log',
    dag=dag
)

task2 = BashOperator(
    task_id='task2',
    bash_command='sleep 5 && echo "task2:"`date` >> /tmp/test.log',
    dag=dag
)

task1 >> task2
EOF
AF_EOF

mkdir -p /run/airflow
chown airflow:airflow /run/airflow

# setup worker service
cat << EOF > /etc/systemd/system/airflow-worker.service
[Unit]
Description=Airflow worker daemon
Requires=network.target

[Service]
User=airflow
Group=airflow
Type=simple
WorkingDirectory=/opt/airflow
Environment=AIRFLOW_HOME=/opt/airflow
ExecStart=/usr/local/bin/pipenv run airflow worker --pid /run/airflow/worker.pid
Restart=on-failure
RestartSec=30s

[Install]
WantedBy=multi-user.target
EOF
systemctl enable airflow-worker.service
systemctl start airflow-worker.service

# setup scheduler service
cat << EOF > /etc/systemd/system/airflow-scheduler.service
[Unit]
Description=Airflow scheduler daemon
Requires=network.target

[Service]
User=airflow
Group=airflow
Type=simple
WorkingDirectory=/opt/airflow
Environment=AIRFLOW_HOME=/opt/airflow
ExecStart=/usr/local/bin/pipenv run airflow scheduler --pid /run/airflow/scheduler.pid
Restart=on-failure
RestartSec=30s

[Install]
WantedBy=multi-user.target
EOF
systemctl enable airflow-scheduler.service
systemctl start airflow-scheduler.service

cat << EOF > /etc/systemd/system/airflow-webserver.service
[Unit]
Description=Airflow webserver daemon
Requires=network.target

[Service]
User=airflow
Group=airflow
Type=simple
WorkingDirectory=/opt/airflow
Environment=AIRFLOW_HOME=/opt/airflow
ExecStart=/usr/local/bin/pipenv run airflow webserver --pid /run/airflow/webserver.pid
Restart=on-failure
RestartSec=30s

[Install]
WantedBy=multi-user.target
EOF
systemctl enable airflow-webserver.service
systemctl start airflow-webserver.service

echo 'url  -> http://192.168.55.115:8080/'
SHELL
end

2. ブラウザでhttp://192.168.55.115:8080/にアクセスして、サンプルDAGのdag_example1をPause状態のOffからOnに変更します。5分程度待つとジョブが実行されます。

○関連情報
・Apache Airflowに関する他の記事はこちらを参照してください。

VagrantでPrometheusをインストールした仮想マシン(Debian Stretch/9.4)を構築する

Prometheusでサーバーの各種情報を監視する事ができます。

〇Prometheusの画面

ブラウザからhttp://192.168.1.108:9090/にアクセスします。

〇構築方法
以下のVagrantfileを使用して、Prometheusをインストールした仮想マシン(Debian Stretch/9.4)を構築します。

Vagrantfile
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "bento/debian-9.4"
  config.vm.hostname = "db94prometheus"
  config.vm.provider :virtualbox do |vbox|
     vbox.name = "db94prometheus"
     vbox.cpus = 4
     vbox.memory = 4096
     vbox.customize ["modifyvm", :id, "--nicpromisc2","allow-all"]
  end
config.vm.network "private_network", ip: "192.168.55.108", :netmask => "255.255.255.0"
config.vm.network "public_network", ip:"192.168.1.108", :netmask => "255.255.255.0"
  config.vm.provision "shell", inline: <<-SHELL
# update packages
apt-get update
#DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade
locale-gen ja_JP.UTF-8
localectl set-locale LANG=ja_JP.UTF-8

# download and install prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.3.2/prometheus-2.3.2.linux-amd64.tar.gz
tar xvfz prometheus-2.3.2.linux-amd64.tar.gz
mv prometheus-2.3.2.linux-amd64 /opt

cat << EOF > /etc/systemd/system/prometheus.service
[Unit]
Description=Prometheus 
Requires=network.target

[Service]
Restart=always
WorkingDirectory=/opt/prometheus-2.3.2.linux-amd64
ExecStart=/opt/prometheus-2.3.2.linux-amd64/prometheus --config.file=prometheus.yml
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
EOF
systemctl enable prometheus
systemctl start prometheus

SHELL
end