设为首页 收藏本站
查看: 1432|回复: 4

[经验分享] Ansible自动化运维工具阐述及配置实现

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2017-1-16 18:16:42 | 显示全部楼层 |阅读模式
    什么是ansible

ansible是一个轻量级的运维管理工具 , 基于Python研发 。可实现对系统的批量管理配置、程序的批量部署、批量的运行命令等功能。 仅需在任意管理主机安装 ansible 程序即可实现批量管理被管控主机且被管控的主机无需客户端。 我们在安装ansible时一定要依托epel源来安装(推荐阿里云),并且在线用yum安装。它基于python开发所以得解决ansible对python编程的各种依赖。

    ansible 特性

1、模块化:调用特定的模块,完成特定的任务;
2、基于Python语言研发主要模块由Paramiko, PyYAML和Jinja2三个核心库实现;
3、部署简单:agentless;
4、支持自定义模块,使用任意编程语言;
5、强大的playbook机制;
6、具有幂等性;

    ansible 基本架构

Modules:模块化
Core Modules 核心模块
Customed Modules 自定义模块
Host Iventory 主机库清单,定义要管理的主机
Files 可以通过配置文件来实现
CMDB 也可以通过外部存储来实现
PlayBooks 剧本,定义每个主机所扮演的角色
Hosts 哪些主机
Roles 哪些角色
Connection Plugins:连接插件,主要连接各管控主机
Email
Loggin
Other

1479642088668938.jpg

    注意,ansible不是服务!千万也不用去想服务的概念

安装及程序环境:

程序:
ansible
ansible-playbook
ansible-doc
配置文件:
/etc/ansible/ansible.cfg
主机清单:
/etc/ansible/hosts
插件目录:
/usr/share/ansible_plugins/

    主机清单说明

vim /etc/ansible/hosts
# Ex 1: Ungrouped hosts, specify before any group headers.
直接给出主机,IP主机名都可以
## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
# Ex 2: A collection of hosts belonging to the 'webservers' group
把几个主机分组,用中括号定义组名
## [webservers]
## alpha.example.org ...
## 192.168.1.100 ...
# If you have multiple hosts following a pattern you can specify
对主机进行通配001:006表示到一个范围
## www[001:006].example.com
# Ex 3: A collection of database servers in the 'dbservers' group
定义一组数据库服务器
## [dbservers]
## db02.intranet.mydomain.net ...
## 10.25.1.56 ...

    基本使用入门,获取模块列表

ansible -doc -l 获取模块列表
ansible-doc -s MOD_NAME 获取指定模块帮助信息

    以ping模块为例,测试

[iyunv@localhost ~]# ansible webserver -m ping
                    //我是定义了webserver组
    172.16.5.103 | UNREACHABLE! => {
        "changed": false,
        "msg": "Failed to connect to the host via ssh.",
        "unreachable": true
    }
    172.16.5.102 | UNREACHABLE! => {
        "changed": false,
        "msg": "Failed to connect to the host via ssh.",
        "unreachable": true
    }
以上的测试结果提示没有通过ssh连接到主机,所以我们得配置基于ssh的公钥认证
因为ansible是基于ssh进行认证的
也可以这样:
ansible all -m ping --ask-pass -c paramiko //你懂的

    设置 SSH 公钥认证,并把生成的公钥拷贝到任意N个主机,实现无密码操作

在Ansible服务端生成密钥,并且复制公钥到节点中。
root@ansible ~]#ssh-keygen //一路回车,文件生成路径root/.ssh/
使用ssh-copy-id命令来复制Ansible公钥到节点中。
ssh-copy-id -i root@172.16.5.102/103/105 //见笑了

    以ping模块再次测试

[iyunv@Centos6 ~]# ansible all -m ping
172.16.5.103 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
172.16.5.102 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
172.16.5.105 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
[iyunv@Centos6 ~]#
ok成功......

    常用模块举例说明1

常用模块:
ping:探测目标主机是否存活;
    举例: ansible all -m ping
command:在远程主机执行命令;
    举例:ansible all -m command -a "ifconfig"
    举例:ansible all -m command -a "useradd centos"
shell:在远程主机上调用shell解释器运行命令,支持shell的各种功能,如管道等
    举例:ansible all -m shell -a "echo centos |passwd --stdin centos"
copy:复制文件,给定内容生成文件,mode, owner, group,follow, ...
    拷贝文件
    举例:ansible all -m copy -a "src=/etc/fstab dest=/tmp/fstab.ansible mode=640"
    生成文件
    举例:ansible all -m copy -a "content='hell\nworld\n' dest=/tmp/fstab.ansible mode=640"
file:设置文件属性
    更改文件属主
    举例:ansible all -m file -a "path=/tmp/fstab.ansible owner=centos"
    删除文件
    举例:ansible all -m file -a "path=/tmp/fstab.ansible state=absent"
    state 用来定义目标文件状态的
    创建指定文件空目录
    举例:ansible all -m file -a "path=/tmp/dir.ansible state=directory"
    链接文件
    举例:ansible all -m file -a "path=/tmp/test.ansible.link src=/tmp/test.ansible
    state=link"
fetch:从远程主机拉取一个文件
    ansible是用来管理多节点的,从远程拉取多个文件到目标主机显然不近乎仁义。所以用scp就能搞定。略过

    常用模块举例说明2

cron:用来管理crontab的周期性任务
    定义一个任务
    举例:ansible all -m cron -a "minute'*/5' job='/usr/sbin/ntpdate 10.1.0.1 &>/dev/null'
         name='sync time'"
         crontab -l
    删除一个任务
    举例:ansible all -m cron -a "name='sync time' state=absent"
    只删除用ansible定义的名
hostname:定义主机名
    举例:
yum:使用yum包管理器,完成程序包管理
    举例:ansible all -m yum -a "name=httpd" 安装
    举例:ansible all -m yum -a "name=httpd state=absent" 删除
service:控制服务,控制服务是否开机自动启动
    举例:ansible all -m service -a "name=httpd state=started enbaled=true"
group:添加或者删除组
    举例:
user:管理组账号
    举例:
setup:收集远程各主机的各种属性之和
    举例:ansible all -m setup
以上内容就到这里,我们该定义一个剧本了

    定义一个PlayBook,我们来唱剧本

    playbook是由一个或多个”play”组成的列表。play的主要功能在于将事先归为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来将,所谓的task无非是调用ansible的一个module。将多个paly组织在一个playbook中,即可以让他们联通起来按事先编排的机制同唱一台大戏。
    YAML是用来写配置文件的,接下来的配置文件都是以yaml为后缀

[iyunv@Centos6 ~]# yum info PyYAML
核心元素:
    Tasks:任务,由模块定义的操作的列表;
    Variables:变量
    Templates:模板,即使用了模板语法的文本文件;
    Handlers:由特定条件触发的Tasks;
    Roles:角色;自包含,有完整独立实体
playbook的基础组件:
        Hosts:运行指定任务的目标主机,可多个;
        remote_user:在远程主机以哪个用户身份执行;
            sudo_user:非管理员需要拥有sudo权限;
        tasks:给出任务列表,执行完一个,执行第二个
            模块,模块参数:
                格式:
                    (1) action: module arguments //任务执行过程
                    (2) module name: arguments //指定运行的模块

    示例;利用playbook指挥三台主机都创建mygrp组

[iyunv@Centos6 ~]# vim group.yaml
- hosts: all //任务运行在所有主机
  remote_user: root //在远程主机以哪个用户执行
  tasks: //任务列表1
  - name: install a group //任务名
    group: name=mygrp system=true //调用group模块创建组mygrp
  - name: install a user //任务名
    user: name=user1 group=mygrp system=true //创建user1 组mygrp
- hosts: webserver //任务运行在webserver组内的主机
  remote_user: root //在远程主机以哪个用户执行
  tasks: //任务列表2
   - name: install httpd package //任务名
     yum: name=httpd //调用yum模块安装httpd
   - name: start httpd service //任务名
     service: name=httpd state=started //调用service模块启动服务
    检查语法,测试运行
annsible-playbook --syntax-check group.yaml
annsible-playbook --list-hosts --list-tasks group.yaml

    示例;利用playbook指挥webserver组内主机安装httpd并监听8080端口

vim httpd.yaml
- hosts: webserver
  remote_user: root
  tasks:
  - name: install httpd package
    yum: name=httpd state=latest
    tags: installpkg //指明跑某个标签 -t installpkg
  - name: install conf file
    copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
    tags: installconf //指明跑某个标签 -t installconf
    notify: restart httpd service  通知给《===httpd
  - name: start httpd service
    service: name=httpd state=started
  handlers: //处理器,也是任务,但是在一定条件下触发
  - name: restart httpd service //handlers名字
    service: name=httpd state=restarted
语法检查,测试运行
annsible-playbook --syntax-check  -t installconf  --list-tags httpd.yaml
annsible-playbook --syntax-check httpd.yaml
annsible-playbook --list-hosts --list-tasks httpd.yaml

    注意:
    handlers:是指在一定条件下触发,指明在一个需要让别人重启服务才生效的任务上使用notify,通知一定是handlers名字
    tags:只执行playbook中指定的tags标签,满足部分需要,多个任务可指明一个同tags
    也可以一次调用两个标签,如下
    annsible-playbook -t installconf,installpkg httpd.yaml

自定义变量Variables,可自定义安装任意程序包

[iyunv@Centos6 ~]# cat name.yaml
- hosts: webserver
  remote_user: root
  vars:
  - pkgname: memcached //playbook中使用的变量Variables
  tasks:
  - name: install a package
    yum: name={{ pakgname }} state=present //自定义变量
[iyunv@Centos6 ~]#
语法测试
ansible-playbook --syntax-check name.yaml
ansible-playbook -e pkgname=httpd/vsftpd/ name.yaml
注意:在执行时命令行中给出的值要优先于playbook内置变量
如:ansible-playbook -e pkgname=httpd name.yaml
检查:rpm -ql httpd memcached

传递给主机单独变量,实现某些主机安装不同程序包

编辑主机清单在每个主机后面指定调用变量并赋值
vim /etc/ansible/hosts
[webserver]
172.16.5.102 pkgname=nginx
172.16.5.103 pkgname=httpd
[webserver:vars] //为一个组内不同主机定义相同变量,效果同上
webserver组内有一组变量vars,其中变量名是pkgname值是memcached
pkgname=memcached
vim name.yaml
    - hosts: webserver
      remote_user: root
      tasks:
      - name: install a package
        yum: name={{ pkgname }} state=present
语法测试
ansible-playbook --syntax-check name.yaml

    Inventory还可以使用参数:
    用于定义ansible远程连接目标主机使用的属性,而非传递给playbook的变量
    如: [webserver]
    172.16.5.102 ansible_ssh_user= ansible_ssh_pass ansible_sudo_pass
    不再是传递给playbook变量,而是主机本身。

playbook模版

模版本身是文本文件,内部嵌套有模板语言脚本(使用模板语言编写jinjia2)
Jinja2 是仿照 Django 模板的 Python 模板语言。 它速度快,被广泛使用,并且提供了可选的沙箱模板执行环境保证安全。只介绍简单使用,不过多阐述,语言啊
jinjia2是用来写模版文件的,接下来的模版文件都是以j2为后缀

语法格式:
        支持字面量:
        字符串:使用单引号或双引号;
        数字:整数、浮点数;
        列表:[item1, item2, ...]
        元组:(item1, item2, ...)
        字典:{key1:value1, key2:value2, ...}
        布尔型:true/false              
        算术运算:
            +, -, *, /, //, %, **
        比较操作:
            ==, !=, >, <, >=, <=   
        逻辑运算:and, or, not

基于模版把nginx配置文件对应的虚拟cpu值改成不是auto

    安装nginx程序包,我们要使用nginx的配置文件当模版
    yum install nginx
    cp /etc/nginx/nginx.conf .
    vim nginx.conf
    worker_processes {{ ansible_processor_vcpus }}; //由auto改成这样
    vim nginx.yaml
    – hosts: webserver
    remote_user: root
    tasks:
    – name: copy a nginx file
    template: src=/root/nginx.conf dest=/tmp/nginx.conf
    语法测试
    ansible-playbook –syntax-check nginx.yaml

完整安装nginx程序,并调用nginx.conf.j2模版

    vim nginx.yaml
    – hosts: nginxserver //指定组
    remote_user: root
    tasks:
    – name: install nginx package //安装nginx程序包
    yum: name=nginx state=latest //调用的yum模块
    – name: install conf file
    template: src=/root/nginx.conf.j2 dest=/etc/nginx.conf //调用的配置文件模版
    tags: ngxconf //标签
    notfiy: reload nginx service //通知让标签干什么
    – name: start nginx service
    service: name=nginx state=started enabled=true //启动服务,并开机启动
    handlers: //触发器,当某个条件满足时将触发,也是任务
    – name: reload nginx service
    shell: /usr/sbin/nginx -s reload
    语法测试
    ansible-playbook –syntax-check nginx.yaml

使用when条件判断语句,判断基于不同发行版使用不同命令来重启nginx服务

vim nginx2.yaml
- hosts: all
  remote_user: root
  tasks:
- name: install nginx package
  yum: name=nginx state=latest
- name: start nginx service on CentOS6
  shell: service nginx start
  when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"
- name: start nginx service
  shell: systemctl start nginx.service
  when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
语法测试
ansible-playbook --syntax-check nginx2.yaml

基于字符串列表给出元素循环:迭代,需要重复执行的任务;
对迭代项的引用,固定变量名为”item”,使用with_item属性给定要迭代的元素;
元素列表有两种:字符串,字典

vim web.yaml
- hosts: webserver
  remote_user: root
  tasks:
  - name: install package
    yum: name={{ item }} state=latest
    with_items:
    - httpd
    - php
    - php-mysql
    - php-mbstring
    - php-gd
语法测试
ansible-playbook --syntax-check web.yaml

基于字典列表给出元素循环:迭代,需要重复执行的任务;
之前我们讲过我们要批量在组内的机器上创建用户是可以的。无非调用user模块并指明组就可以,但是在不同组内的机器上创建的,可能用户名与组名都是不相同的,那我们想要它都同样该怎么办呢?
这个时候我们就可以通过固定变量item来实现 增加两条name,一个指明用户,一个指明组名

vim creat.yaml
- hosts: webserver
  remote_user: root
  tasks:
  - name: creat groups //第一个任务
  yum: name={{ item }} state=latest
  with_items:
  - groupx1
  - groupx2
  - groupx3
  - name: creat users //第二个任务
user: name={{ item.name }} group={{ item.group }} state=present
  with_items: //元素列表
  - {name: 'userx1', group: 'groupx1'} //name键值队
  - {name: 'userx1', group: 'groupx1'} //name键值队
  - {name: 'userx1', group: 'groupx1'} //name键值队
语法测试:ansible-playbook --check creat.yaml
注释:
item.name表示调用第一个键name里的值userx1
item.group表示调用第一个键group里的值groupx1

角色(自包含,按照目录结构来组织)
指定由哪些主机去对应的完成哪个已定义好的角色

roles是以特定的层级目录结构进行组织的tasks、variables、handlers、templates…
role_name/
files/:
存储由copy或script等模块调用的文件;
tasks/:
此目录中至少应该有一个名为main.yml的文件,用于定义各task;其它的文件需要由main.yml进行“包含”调用;
handlers/:
此目录中至少应该有一个名为main.yml的文件,用于定义各handler;其它的文件需要由main.yml进行“包含”调用;
vars/:
此目录中至少应该有一个名为main.yml的文件,用于定义各variable;其它的文件需要由main.yml进行“包含”调用;
templates/:
存储由template模块调用的模板文本;
meta/:
此目录中至少应该有一个名为main.yml的文件,定义当前角色的特殊设定及其依赖关系;其它的文件需要由main.yml进行“包含”调用;
default/:
此目录中至少应该有一个名为main.yml的文件,用于设定默认变量;

举例:在webserver组内机器分别各自安装nginx,memcached,msql-server通过roles调用tasks
创建目录
mkdir -pv ./{nginx,memcached,httpd,mysql}/{files,templates,vars,handlers,meta,tasks,default}

安装nginx
1、在nginx目录tasks目录下创建main.yml文件
    [iyunv@Centos6 tasks]# vim main.yml
    - name: copy nginx package to remote host //先拷贝安装程序
      copy: src=nginx-1.10.1-1.el7.x86_64.rpm
            dest=/tmp/nginx-nginx-1.10.1-1.el7.x86_64.rpm
      tags: cppkg
    - name: install nginx package //再安装程序包
      yum: name=/tmp/nginx-1.10.0-1.el7.nginx.x86_64.rpm  state=present
    - name: install conf file nginx.conf //然后提供配置文件
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
      tags: nginxconf //加了一个标签,按需执行
      notify: reload nginx service //通知标签要干什么,我们需要在handlers目录下创建触发器
    - name: install conf file default.conf //再提供nginx默认文件
      template: src=default.conf.j2 dest=/etc/nginx/conf.d/default.conf
      tags: nginxconf
      notify: reload nginx service
    - name: start nginix service //启动服务
      service : name=nginx enabled=true state=started
2、在nginx目录handlers目录下创建main.yml文件
      [iyunv@Centos6 handlers]# cat main.yml
        - name: reload nginx service
          service: name=nginx state=restarted
        [iyunv@Centos6 handlers]#
  3、拷贝nginx.conf文件到templates目录下做模版
        [iyunv@Centos6 roles]# cp /etc/nginx/nginx.conf nginx/templates/nginx.conf.j2
        更改 worker_processes {{ ansible_processor_vcps }};
  4、拷贝default.conf文件到templates目录下做模版
          [iyunv@Centos6 roles]# cp /etc/nginx/conf.d/default.conf nginx/default/default.conf.j2
          更改    listen       {{ nginxport }};  //变量定义
  5、nginx/vars目录下创建main.yml 调用变量
          写入 nginxport: "8090"
  6、在ansible目录下创建nginx.yml文件来调用以上各种组织好的nginx角色
          [iyunv@Centos6 roles]# vim nginx.yml
                - hosts: webserver
                  remote_user: root
                  roles: //定义角色
                  - { role: nginx, ngxport: 8080 }//即能调角色,又能向角色传变量
                  - nginx //角色调用
  7、编辑ansible.cfg文件启用roles_path让roles去找所定义的文件
          [iyunv@Centos6 ansible]# vim ansible.cfg
          启用把前面注释去掉 roles_path    = /etc/ansible/roles
8、要注意,避免错误,最好定义好文件后各自做个语法测试
9、然后就可以让剧本跑一遍了
10、确保你的系统selinux是disabled,不然服务起不来
     ansible-playbook --syntax-check nginx.yml

安装memcached
[iyunv@Centos6 memcached]# ls ../memcached/*
../memcached/handlers:
main.yml
- name: reload memcached
  service: name=memcached state=restarted
../memcached/tasks:
main.yml
- name: install memcached
  yum: name=memcached state=latest
- name: install conf file
  template: src=memcached.j2 dest=/etc/sysconfig/memcached
  tags: mcconf
  notify: reload memcached
- name: start memcached service
  service: name=memcached state=started enabled=true
../memcached/templates:
memcached.j2
    PORT="11211"
    USER="memcached"
    MAXCONN="1024"
    CACHESIZE="{{ ansible_memtotal_mb //4 }}"
    OPTIONS=""
[iyunv@Centos6 memcached]#

安装mysql
vim mysql/tasks/main.yml
mysql/tasks:
main.yml
- name: install mysql-server
  yum: name=mysql-server state=latest
  when: ansible_distribution == "Centos" and ansible_distribution_major_version == "6"
- name: install mariadb-server
  yum: name=mariadb-server state=latest
  when: ansible_distribution == "Centos" and ansible_distribution_major_version == "7"
- name: start mysql service
  service: name=mysqld state=started
  when: ansible_distribution == "Centos" and ansible_distribution_major_version == "6"
- name: start mariadb service
  service: name=mariadb state=started
  when: ansible_distribution == "Centos" and ansible_distribution_major_version == "7"
[iyunv@Centos6 ansible]# vim mysql.yml
    - hosts: webserver
      remote_user: root
      roles:
      - mysql
语法测试:
ansible-playbook --syntax-check  mysql.yml

done!!!

以上配置环境皆基于CentOS 7.2来实现并完成。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-329324-1-1.html 上篇帖子: ansible 安装部署详解(待更新) 下篇帖子: 自动化运维工具ansible--笔记一之简介安装/常用模块
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表