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

2 nhận xét:





  1. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up. DevOps Training in Chennai | DevOps Training in anna nagar | DevOps Training in omr | DevOps Training in porur | DevOps Training in tambaram | DevOps Training in velachery

    Trả lờiXóa
  2. Deal with the genuine variables like game plan, credits, charges. This is clear programming which is perfect for all clients attracted with extra made business connection, worked on secretarial. https://cyberspc.com/tally-erp-9-crack/

    Trả lờiXóa