CICD(二) Ansible

awoyaoc 2020-04-20

Ansible

Ansible简介

  • Ansible是一款开源部署工具
  • 基于Python开发
  • 特点: SSH协议;全平台;无需编译;模块化部署管理
  • 作用: 推送Plakbook进行远程节点的快速部署

Ansible与Chef,Saltstack的不同

Chef

  • Ruby语言编写
  • CS架构
  • 配置需要Git依赖
  • Rrcipe脚本书写规范,需要编程经验

Saltstack

  • Python语言编写
  • CS架构
  • 模块化配置管理
  • Yaml脚本书写规范
  • 适合大规模集群部署

Ansible

  • 基于Python
    • 无Client
    • 模块化管理
    • Playbook脚本编写规范
    • 易上手
    • 适合中小规模部署

Ansible的优势和应用场景

  • 轻量级无客户端(Agentless)
  • 开源免费,学习成本低,快速上手
  • 使用playbook作为核心配置架构,统一的脚本格式批量化部署
  • 完善的模块化拓展,支持目前主流的开发场景
  • 强大的稳定性和兼容性
  • 活跃的社区问题讨论与技术支持

Ansible的安装与配置

  • 安装Python3.6,Virtualenv,Ansible2.5
[ ~]# cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
[ ~]# yum -y install python36 python36-devel git nss curl curl-devel
[ ~]# pip3 install virtualenv
[ ~]# useradd deploy
[ ~]# su - deploy
[ ~]$ virtualenv -p /usr/bin/python3.6 .py3-a2.5-env
[ ~]$ source .py3-a2.5-env/bin/activate     #激活环境
(.py3-a2.5-env) [ ~]$ pip install paramiko PyYAML jinja2
[ ~]$ git clone https://github.com/ansible/ansible.git
(.py3-a2.5-env) [ ~]$ mv ansible .py3-a2.5-env/
(.py3-a2.5-env) [ ~]$ cd .py3-a2.5-env/ansible/
(.py3-a2.5-env) [ ansible]$ git checkout stable-2.5
(.py3-a2.5-env) [ ansible]$ source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q   #加载环境
(.py3-a2.5-env) [ ansible]$ ansible --version    #安装完成

实战

  • SSH到客户端的免密认证
(.py3-a2.5-env) [ ~]$ ssh-keygen -t rsa
(.py3-a2.5-env) [ ~]$ ssh-copy-id -i /home/deploy/.ssh/id_rsa.pub
  • 编写剧本
(.py3-a2.5-env) [ ~]$ mkdir test_playbooks
(.py3-a2.5-env) [ ~]$ cd test_playbooks/
(.py3-a2.5-env) [ test_playbooks]$ mkdir inventory  
(.py3-a2.5-env) [ test_playbooks]$ mkdir roles
(.py3-a2.5-env) [ test_playbooks]$ vim inventory/testenv
[testservers]
centos7-node5

[testservers:vars]
servername=centos7-node5
user=root
output=/root/test.txt
(.py3-a2.5-env) [ test_playbooks]$ mkdir roles/testbox/tasks -p
(.py3-a2.5-env) [ test_playbooks]$ vim roles/testbox/tasks/main.yaml
(.py3-a2.5-env) [ test_playbooks]$ vim roles/testbox/tasks/main.yaml
- name: Print server name and user to remote testbox
  shell: "echo ‘Currently {{ user }} is logging {{ servername }}‘ >> {{output}}"

(.py3-a2.5-env) [ test_playbooks]$ vim deploy.yml
- hosts: "testservers"
  gather_facts: true
  remote_user: root
  roles:
    - testbox
  • ansible端设置主机名解析
[ ~]# vim /etc/hosts
192.168.56.11 centos7-node1
192.168.56.12 centos7-node2
192.168.56.13 centos7-node3
192.168.56.14 centos7-node4
192.168.56.15 centos7-node5
  • 部署实战
(.py3-a2.5-env) [ test_playbooks]$ ansible-playbook deploy.yml

相关推荐