Thứ Bảy, 27 tháng 2, 2016

Ansible

Phần 1 - Cài đặt và cấu hình

Ansible là gì?

Ansible đang là công cụ Configuration Management khá nổi bật hiện nay.
  • Là công cụ mã nguồn mở dùng để quản lý cài đặt, cấu hình hệ thống một cách tập trung và cho phép thực thi câu lệnh điều khiển.
  • Sử dụng SSH (hoặc Powershell) và các module được viết bằng ngôn ngữ Python để điểu khiển hệ thống.
  • Sử dụng định dạng JSON để hiển thị thông tin và sử dụng YAML (Yet Another Markup Language) để xây dựng cấu trúc mô tả hệ thống.

Đặc điểm của Ansible

  • Không cần cài đặt phần mềm lên các agent, chỉ cần cài đặt tại master.
  • Không service, daemon, chỉ thực thi khi được gọi
  • Bảo mật cao ( do sử dụng giao thức SSH để kết nối )
  • Cú pháp dễ đọc, dễ học, dễ hiểu

Yêu cầu cài đặt

  • Hệ điều hành: Linux (Redhat, Debian, Ubuntu, Centos, ...), Windows
  • Thư viện Jinja2: dùng để xây dựng template cấu hình
  • Thư viện PyYAML: hỗ trợ cấu trúc YAML
  • Python 2.4 trở lên

Cài đặt Ansible

  • Trên CentOS:
    • Cài đặt EPEL repo
    • Cài đặt thông qua yum:
sudo yum install ansible 
  • Trên Ubuntu:
Cấu hình PPA, cài đặt: 
sudo apt-get install software-properties-common
sudo apt-add-repository ppa:ansible/ansible
sudo apt-get update
sudo apt-get install ansible 
Trên các phiên bản Ubuntu cũ, gói software-properties-common có tên khác là python-software-properties

Cấu hình

Demo sử dụng hệ điều hành Ubuntu 14.04, với các hệ điều hành khác cũng hoàn toàn tương tự. 
Server master: 192.168.1.100  
Server agent: 192.168.1.101
  • Tạo tài khoản truy cập SSH trên agent
Do policy của hệ thống giới hạn tài khoản root truy cập cũng như để thuận tiện cho việc quản lý (tránh dùng chung account của người quản trị) thì nên tạo 1 tài khoản khác phục vụ cho ansible
Tạo tài khoản:
sudo adduser ansible
Cấu hình sudo cho phép tài khoản ansible sử dụng không cần password 
sudo vi /etc/sudoers.d/ansible
ansible ALL=(ALL)   NOPASSWD:ALL  
  • Tạo ssh key
Để thuận tiện cho việc sử dụng Ansible cũng như giới hạn 1 số hệ thống chỉ cho phép xác thực qua key. (Ansible có hỗ trợ kết nối thông qua password)

Tạo ssh keyfile: ( trên master ) 
ssh-keygen -C "ansible@master"
Enter file in which to save the key (/home/ubuntu/.ssh/id_rsa): '/etc/ansible/ansible_key'
...
Lý do không đặt ssh key ở thư mục mặc định là do rất có thể có nhiều người quản trị cùng tham gia quản lý.)
Copy keyfile sang agent: 
ssh-copy-id -i /etc/ansible/ansible_key.pub ansible@192.168.1.101
Kiểm tra:
ssh -i /etc/ansible/ansible_key ansible@192.168.1.101
  • Cấu hình host và group
Ansible lưu thông tin những hệ thống trong file /etc/ansible/hosts (inventory) theo cấu trúc dạng INI như sau: 
mail.example.com

[webservers]
foo.example.com  
bar.example.com

[dbservers]
one.example.com  
two.example.com  
three.example.com 
Trong đó: 
*.example.com: hostname của các host (phải cấu hình tiếp trong file /etc/hosts để xác định địa chỉ IP) 
[webservers], [dbservers]: là các group 

Ở ví dụ demo này, cấu hình /etc/ansible/hosts như sau:
[webservers]
web1 ansible_ssh_host=192.168.1.101
ansible_ssh_private_key_file=ansible_key
ansible_ssh_user=ansible
List các tham số hỗ trợ: inventory parameters

Sử dụng các lệnh cơ bản
ansible web1 -m ping
ansible webservers -m ping
ansible all -m ping
ansible web1 -m command -a 'df -h'
ansible web1 -s -m command -a 'fdisk -l'
ansible -i /etc/ansible/hosts all -m ping
Chú ý:
  • Ansible cho phép chỉ định 1 host, 1 group hoặc tất cả (all) khi thực thi
  • -m: lựa chọn sử dụng module
  • -a: tham số gửi vào module
  • -s: sử dụng sudo
  • -i: chỉ định inventory file (mặc định /etc/ansible/hosts)

Phần 2 - Playbook

Về Playbook

Playbook thông thường là những tấm bảng ghi sơ đồ vị trí, chiến thuật di chuyển của từng cầu thủ mà các HLV sử dụng để truyền đạt cho cầu thủ (nếu bạn xem đá bóng). Ví dụ như Willian đá hộ công, Eden Hazard đột phá cánh trái hay Branislav Ivanović đá hậu vệ.

Ansible sử dụng khái niệm Playbook cũng mang ý nghĩa tương tự. Việc triển khai hệ thống mới cũng tương tự như sơ đồ chiến thuật, các group [webservers], [databases] cũng như tuyến tiền đạo, hậu vệ, các dịch vụ cũng như kết nối tới các thành phần khác nhau trong hệ thống của từng server cũng giống nhiệm vụ của một cầu thủ trên sân.

Ansible Playbook được viết theo cấu trúc YAML, một cú pháp dễ đọc, dễ viết hơn so với JSON, XML. Dưới đây là ví dụ về YAML:
---
# An employee record
name: Example Developer  
job: Developer  
skill: Elite  
employed: True  
foods:  
    - Apple
    - Orange
    - Strawberry
    - Mango
languages:  
    ruby: Elite
    python: Elite
    dotnet: Lam
Xem thêm về YAML syntax. Bắt đầu file yaml bằng ---. Sử dụng indent là 2 space.

Ví dụ
Đây là file webservers.yml, 1 playbook cho dịch vụ apache. Playbook này có 1 play, dùng cho hệ điều hành Redhat, CentOS
---
- hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  tasks:
  - name: ensure apache is at the latest version
    yum: pkg=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running (and enable it at boot)
    service: name=httpd state=started enabled=yes
  handlers:
    - name: restart apache
      service: name=httpd state=restarted
Giải thích:

  • hosts: xác định đối tượng sẽ thực thi playbook này.
  • vars: các biến dùn trong play, trong ví dụ này các biến sẽ được dùng để cấu hình apache
  • tasks: liệt kê các task cần thực hiện
  • name: tên của task
  • yum, template, service: các module sử dụng
  • notify: giống như trigger, để gọi đến 1 task khác khi task hiện tại thực hiện thành công.
  • handlers: khai báo các task notify
1 play gồm danh sách các task được thực thi theo thứ tự từ trên xuống. Nếu xảy ra lỗi ở task nào thì host đang thực thi sẽ bị dừng lại mà không ảnh hưởng đến các host khác.
Có thể viết tách dòng với các tham số truyền vào module
- name: ensure apache is at the latest version
  yum:
    pkg: httpd
    state: latest
Chạy playbook:
ansible-playbook webserver.yml 
Ví dụ 1 playbook có nhiều play:
---
- hosts: webservers
  tasks:
  - name: ensure apache is at the latest version
    yum: pkg=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf

- hosts: databases
  tasks:
  - name: ensure postgresql is at the latest version
    yum: name=postgresql state=latest
  - name: ensure that postgresql is started
    service: name=postgresql state=running
Cấu trúc 1 playbooks chuẩn:
 production                # inventory file for production servers  
stage                     # inventory file for stage 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
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""
Trong đó:

  • production: giống file /etc/ansible/hosts, liệt kê group, host
  • group_vars/*: đặt các biến chung cho cùng 1 nhóm, ví dụ [webservers] có biến listen_port: 80
  • host_vars/*: đặt các biến riêng cho từng host
  • roles/*: đặt các role, ví dụ các host trong [webservers] gọi đến role webtier

Lợi ích:

  • Tách biệt các hệ thống, 1 hệ thống là 1 project riêng biệt
  • Việc tách role giúp dễ dàng quản lý, phát triển
  • Tái sử dụng tốt, chỉ cần sửa thông tin host, vars
Ví dụ:
lamp_simple/  
├── group_vars
│   ├── all
│   └── dbservers
├── hosts
├── LICENSE.md
├── README.md
├── roles
│   ├── common
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── templates
│   │       └── ntp.conf.j2
│   ├── db
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── templates
│   │       └── my.cnf.j2
│   └── web
│       ├── handlers
│       │   └── main.yml
│       ├── tasks
│       │   ├── copy_code.yml
│       │   ├── install_httpd.yml
│       │   └── main.yml
│       └── templates
│           └── index.php.j2
└── site.yml
Bạn có thể xem thêm các ví dụ khác tại ansible examples

Configuration Management

Configuration Management (CM) là gì? Tại sao phải dùng tới CM? Hạn chế của nó cũng như ứng dụng trong Cloud Computing. Chúng ta sẽ cùng trả lời các câu hỏi trên trong bài viết về Configuration Management.

Configuration Management là gì?

Configuration management (CM) là công cụ thực hiện việc thay đổi trạng thái hiện tại của hệ thống sang trạng thái được xác định trước. Hay nói cách khác, là công cụ hỗ trợ, cấu hình, cài đặt hệ thống một cách tự động.

Configuration management tools

Có rất nhiều công cụ như Ansible, Chef, Puppet, Saltstack ... Loạt bài viết này sẽ không tập trung vào việc so sánh các công cụ CM mà chỉ hướng dẫn bạn cách cài đặt và sử dụng Ansible.

Tại sao lại cần Configuration management?

Ví dụ một ngày sếp bạn vào và bảo bạn triển khai 1 hệ thống LAMP stack gồm 2 server, 1 web và 1 database. OK không vấn đề gì, chỉ cần yum/apt, sửa config apache, php, mysql,.. bạn hoàn thành công việc.

Rồi một ngày khác sếp bạn yêu cầu bạn mở rộng triển khai sang n webserver, m database với cấu hình keepalive, HA, replication database loằng ngoằng... "Anh đùa em?". Không !! Nhưng bạn vẫn hoàn thành công việc.

Lại một ngày khác, sếp bạn vào và nói: "Chú dựng cho anh 1 hệ thống tương tự như vậy nữa nhé. Số lượng server tăng gấp đôi". Và bạn đã khóc

Giờ thì bạn đã hiểu tại sao lại có Ansible, Saltstack rồi chứ ... :D

Lợi ích của configuration management


  • Giúp thực hiện công việc triển khai hệ thống đơn giản và thuận tiện.
  • Hạn chế những công đoạn lặp lại, tiết kiệm thời gian
  • Có thể sử dụng lại cho những hệ thống tương tự.
  • Linh hoạt, mềm dẻo trong quản lý.

So sánh với shell script (Linux)

Thế shell script thì sao ? Tôi vẫn dùng shell script để triển khai hệ thống. Có vấn đề gì đâu ?

Đúng, shell script vẫn tốt. Nhưng hãy tưởng tượng bạn có 10 server, bạn phải download script trên từng server rồi thực thi script. Tiếp tục, ví dụ 10 server đó của bạn có Ubuntu, CentOS, thì chí ít bạn lại phải có 2 version shell script, như apt >< yum, gói Apache trên Ubuntu là apache2, trên CentOS là httpd... Rồi thì version hệ điều hành khác nhau, như Ubuntu 12.04, 14.04, CentOS thì 5, 6, 7. Bạn cần chục version khác nhau của shell script? (hoặc bạn phải if/else mệt nghỉ). Việc maintaince code rất khó khăn.

Với những công cụ như Ansible, Chef... hỗ trợ sẵn việc xác định distro, phiên bản cũng như sử dụng những cấu trúc linh hoạt, dễ đọc như yaml, jinja2 giúp đỡ rất nhiều cho người quản trị để xây dựng kịch bản hệ thống, maintaince code cũng như tái sử dụng.

Có hạn chế gì không ?

Mặc dù rất tốt nhưng CM không phải là vạn năng. Nếu không phải triển khai 1 hệ thống đủ lớn, hoặc chỉ phải thực hiện trên 1, 2 server thì thực sự không cần thiết dùng đến CM. Viết ra kịch bản có khi tiêu tốn nhiều thời gian hơn việc bạn thực hiện nó bằng lệnh.

Trong những tình huống như hệ thống gặp sự cố hay troubleshooting thì CM không có nhiều tác dụng. Đó là những tình huống cần sự cẩn thận, tránh những sai sót không đáng có.

CM với Cloud Computing

Cloud computing mang đến cho bạn khả năng tạo các server ảo hóa một cách nhanh chóng. Chỉ 1 nút bấm, bạn đã có 10 đến hàng trăm cloud server sẵn sàng phục vụ. Với tốc độ phát triển chóng mặt cùng với cạnh tranh quyết liệt trong việc cung cấp dịch vụ trên Internet, những yêu cầu của sếp như ví dụ trên sẽ xảy ra thường xuyên với những deadline ngắn hạn. Là nhà cung cấp dịch vụ trên nền điện toán đám mây, VCCloud hiểu rằng việc tự động hóa các thao tác cài đặt, cấu hình, triển khai và mở rộng với CM sẽ giúp tiết kiệm rất nhiều thời gian và tiền bạc.

Thứ Sáu, 26 tháng 2, 2016

How to Install Nginx on Ubuntu 14.04 LTS

Nginx is a free, open source, high-performance web server. Need HTTP and HTTPS but don’t want to run Apache? Then nginx may be your next go-to, at least for Linux.

Pre-Flight Check

  • These instructions are intended specifically for installing nginx on Ubuntu 14.04 LTS.
  • I’ll be working from a Liquid Web Self Managed Ubuntu 14.04 server, and I’ll be logged in as root.

Step #1: Install nginx

First, you’ll follow a simple best practice: ensuring the list of available packages is up to date before installing anything new.
sudo apt-get -y update
Then it’s a matter of just running one command for installation via apt-get:

sudo apt-get -y install nginx

Step #2: Find Your IP Address; Visit Your Site

Once the installation is complete the nginx service should automatically start and begin listening on port 80. 
Find your server’s IP address run the following command:
ip addr show eth0 | grep inet
In this case we are assuming that eth0 is configured with the primary public IP of your server. Your result may look similar to:

inet xxx.xxx.xxx.xxx/22 brd yyy.yyy.yyy.yyy scope global eth0
Where xxx.xxx.xxx.xxx is the IP address of your server.
Verify that nginx is running by visiting http://xxx.xxx.xxx.xxx. For example: http://1.2.3.4.
You should receive a page similar to:

Step #3: Manage the nginx Service

Start the nginx Service:
service nginx start
Stop the nginx Service:

service nginx stop
Restart the nginx Service:

service nginx restart
Check the Status of the nginx Service:

service nginx status
Assure that nginx starts at boot:

update-rc.d nginx defaults
When running the last command you may receive:

System start/stop links for /etc/init.d/nginx already exist.
The above error simply means that nginx is already configured to start when the server boots.

MongoDB Munin Plugin

A plugin is available that provide metrics for:

  • B-Tree stats
  • Current connections
  • Memory usage
  • Database operations (inserts, updates, queries etc.)

The plugin can be installed on each node where MongoDB. For requirements and instructions to installing the MongoDB Munin Plugin.

Check your setup

After installing the plugin and making the configuration changes, force the server to update the information to check that your setup is correct using the following:
sudo -u munin /usr/share/munin/munin-update
If everything is set up correctly, you will get a chart like this:

Plugins

  • mongo_ops : operations/second
  • mongo_mem : mapped, virtual and resident memory usage
  • mongo_btree : btree access/misses/etc...
  • mongo_conn : current connections
  • mongo_lock : write lock info
  • mongo_docs : number of documents (inserted, updated...)

Requirements

  • MongoDB 2.4+
  • python/pymongo

Installation (ubuntu)

Install pip:

sudo apt-get install build-essential python-dev python-setuptools
sudo easy_install pip
sudo pip install --upgrade virtualenv 

Install pymongo:

sudo pip install pymongo

Install plugins:

git clone https://github.com/comerford/mongo-munin.git /tmp/mongo-munin
sudo cp /tmp/mongo-munin/mongo_* /usr/share/munin/plugins
sudo ln -sf /usr/share/munin/plugins/mongo_btree /etc/munin/plugins/mongo_btree
sudo ln -sf /usr/share/munin/plugins/mongo_conn /etc/munin/plugins/mongo_conn
sudo ln -sf /usr/share/munin/plugins/mongo_lock /etc/munin/plugins/mongo_lock
sudo ln -sf /usr/share/munin/plugins/mongo_mem /etc/munin/plugins/mongo_mem
sudo ln -sf /usr/share/munin/plugins/mongo_ops /etc/munin/plugins/mongo_ops
sudo ln -sf /usr/share/munin/plugins/mongo_docs /etc/munin/plugins/mongo_docs
sudo chmod +x /usr/share/munin/plugins/mongo_*
sudo service munin-node restart
Check if plugins are running:
munin-node-configure | grep "mongo_"
Test plugin output:
munin-run mongo_ops

Configuration

How to configure custom db connection?
munin-node can set env value in below file: /etc/munin/plugin-conf.d/munin-node
[mongo_*]
env.MONGO_DB_URI mongodb://user:password@host:port/dbname

How to Install MongoDB on Ubuntu 14.04 LTS

MongoDB is a NoSQL database intended for storing large amounts of data in document-oriented storage with dynamic schemas. NoSQL refers to a database with a data model other than the tabular format used in relational databases such as MySQL, PostgreSQL, and Microsoft SQL. MongoDB features include: full index support, replication, high availability, and auto-sharding.

Pre-Flight Check

  • These instructions are intended for installing MongoDB on a single Ubuntu 14.04 LTS node.
  • I’ll be working from a Liquid Web Core Managed Ubuntu 14.04 LTS server, and I’ll be logged in as a non-root user, but with sudo access. For information on giving a user sudo access visit our page on How to Add a User and Grant Root Privileges on Ubuntu 14.04

Step #1: Setup a the Package Database

First we’ll import the MongoDB public key used by the package management system:
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
Create a list file for MongoDB.

Create the /etc/apt/sources.list.d/mongodb-org-3.2.list list file using the command appropriate for your version of Ubuntu:

Ubuntu 12.04

echo "deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

Ubuntu 14.04

echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
Now reload the package database:

sudo apt-get update

Step #2: Install Latest Stable Version MongoDB

At this point, installing MongoDB is as simple as running just one command:
sudo apt-get install -y mongodb-org
If you’d like MongoDB to auto-update with apt-get than you’re done with the installation. But, it’s possible to ‘pin’ the version of MongoDB you just installed to prevent apt-get from auto-updating.

echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-org-shell hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections

Step #3: Get MongoDB Running

Start-Up MongoDB:
sudo service mongod start
Check MongoDB Service Status:

sudo service mongod status
Summary List of Status Statistics (Continuous):

mongostat
Summary List of Status Statistics (5 Rows, Summarized Every 2 Seconds):

mongostat --rowcount 5 2
Enter the MongoDB Command Line:

mongo
By default, running this command will look for a MongoDB server listening on port 27017 on the localhost interface. 
If you’d like to connect to a MongoDB server running on a different port, then use the –port option. For example, if you wanted to connect to a local MongoDB server listening on port 22222, then you’d issue the following command:
mongo --port 22222
Shutdown MongoDB:

sudo service mongod stop
Restart MongoDB:

sudo service mongod restart
Thanks,

How to Remove (Delete) a User on Ubuntu 14.04 LTS


Pre-Flight Check

  • These instructions are intended specifically for removing a user on Ubuntu 14.04 LTS.
  • I’ll be working from a Liquid Web Core Managed Ubuntu 14.04 LTS server, and I’ll be logged in as root.

Step 1: Delete the User

It’s just one simple command to add a user. In this case, we’re adding a user called madman:

userdel madman
If you want to remove all of the files for the user, then use -r:

userdel -r madman

Step 2: Remove Root Privileges to the User

visudo
Find the following code:

## Allow root to run any commands anywhere
root ALL=(ALL:ALL) ALL
madman ALL=(ALL:ALL) ALL
In this case, we’re removing root privileges from the user madman. Remove the following:

madman ALL=(ALL:ALL) ALL
Then exit and save the file with the key commands Ctrl-x, Y, enter.

How to Add a User and Grant Root Privileges on Ubuntu 14.04

Pre-Flight Check

  • These instructions are intended specifically for adding a user on Ubuntu 14.04 LTS.
  • I’ll be working from a Liquid Web Core Managed Ubuntu 14.04 LTS server, and I’ll be logged in as root.

Step 1: Add the User

It’s just one simple command to add a user. In this case, we’re adding a user called madman:

adduser madman
First you will be prompted to enter the user’s password (twice); do this step. Next you’ll be prompted to enter in the user’s information. This step is not required, and pressing enter fills the field with the default information:

Adding user 'madman' ...
Adding new group 'madman' (1001) ...
Adding new user 'madman' (1001) with group 'madman' ...
Creating home directory '/home/madman' ...
Copying files from '/etc/skel' ...
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for madman
Enter the new value, or press ENTER for the default
Full Name []: User
Room Number []:
Work Phone []:
Home Phone []:
Other []:
When prompted with the following question, enter Y then hit enter to continue.

Is the information correct? [Y/n] Y

Step 2: Grant Root Privileges to the Use

visudo
Find the following code:

# User privilege specification
root ALL=(ALL:ALL) ALL
In this case, we’re granting root privileges to the user madman. Add the following below that code:

madman ALL=(ALL:ALL) ALL
Then exit and save the file with the key commands Ctrl-x, Y, enter.
If you’ve followed the instruction above correctly, then you should now have a user setup by the name of madman which can use sudo to run commands as root!