zoukankan      html  css  js  c++  java
  • 第二十五章 ansible基础

    一、Ansible概述

    1.什么是Ansible

    Ansible是一个自动化统一配置管理工具,自动化主要体现在Ansible集成了丰富模块以及功能组件,可以通过一个命令完成一系列的操作,进而能减少重复性的工作和维护成本,可以提高工作效率。

    2.自动化工具

    1.puppet 学习难,安装ruby环境难,没有远程执行功能
    2.ansible 轻量级,大规模环境下只通过ssh会很慢,串行的
    3.saltstack 一般选择salt会使用C/S结构的模式,salt-master和salt-minion,并行的,大规模批量操作的情况下,会比Ansible速度快一些,底层使用的是zero-MQ消协队列

    3.手动运维和自动运维

    #手动运维
    在之前,我们学习了如何安装nginx。但是我们使用的是yum安装的方式,在以前,运维需要规范,需要统一配置管理,我们只能使用源码安装方式,便于我们去管理,源码安装,如果是单台还好,一会也就装完了,如果此时,生产环境压力骤增,需要扩展100台web节点(源码安装100台nginx)我们该如何操作?

    #自动运维可以做到
    1.批量命令执行
    2.批量安装服务
    3.批量配置
    4.批量任务执行
    5.批量代码部署

    #自动化运维优点
    1.提高工作效率
    2.提高工作准确性
    3.降低人工成本
    4.减少重复工作

    4.Ansible的功能及优点

    1.远程执行
    批量执行远程命令,可以对多台主机进行远程操作

    2.配置管理
    批量配置软件服务,可以进行自动化方式配置,服务的统一配置管理,和启停

    3.事件驱动
    通过Ansible的模块,对服务进行不同的事件驱动
    比如:
    1)修改配置后重启
    2)只修改配置文件,不重启
    3)修改配置文件后,重新加载
    4)远程启停服务管理

    4.管理公有云
    通过API接口的方式管理公有云,不过这方面做的不如saltstack.
    saltstack本身可以通过saltcloud管理各大云厂商的云平台

    5.二次开发
    因为语法是Python,所以便于运维进行二次开发

    6.任务编排
    可以通过playbook的方式来统一管理服务,并且可以使用一条命令,实现一套架构的部署

    7.跨平台,跨系统
    几乎不受到平台和系统的限制,比如安装apache和启动服务

    在Ubuntu上安装apache服务名字叫apache2
    在CentOS上安装apache服务名字叫httpd

    在CentOS6上启动服务器使用命令:/etc/init.d/nginx start
    在CentOS7上启动服务器使用命令:systemctl start nginx

    二、Ansible架构

    1.组成结构

    1.连接插件connection plugins用于连接主机 用来连接被管理端
    2.核心模块core modules连接主机实现操作, 它依赖于具体的模块来做具体的事情
    3.自定义模块custom modules根据自己的需求编写具体的模块
    4.插件plugins完成模块功能的补充
    5.剧本playbookansible的配置文件,将多个任务定义在剧本中,由ansible自动执行
    6.主机清单inventor定义ansible需要操作主机的范围

     

    2.Ansible执行流程

    1.Ansible读取playbook剧本,剧本中会记录对哪些主机执行哪些任务。
    2.首先Ansible通过主机清单找到要执行的主机,然后调用具体的模块。
    3.其次Ansible会通过连接插件连接对应的主机并推送对应的任务列表。
    4.最后被管理的主机会将Ansible发送过来的任务解析为本地Shell命令执行。

     

    三、搭建Ansible

    1.环境准备

    主机名IP身份
    m01 10.0.0.61 Ansible 控制端
    web01 172.16.1.7 Ansible 被控端
    web03 172.16.1.9 Ansible 被控端

    2.安装Ansible

    [root@m01 ~]# yum install -y ansible

    3.Ansible命令

    # ansible <host-pattern> [options]
    --version   #ansible版本信息
    -i          #主机清单文件路径,默认是在/etc/ansible/hosts
    -m          #使用的模块名称,默认使用command模块
    -a          #使用的模块参数,模块的具体动作
    -k          #提示输入ssh密码,而不使用基于ssh的密钥认证
    -C          #模拟执行测试,但不会真的执行
    -T          #执行命令的超时

    #查看Ansible版本及模块路径
    [root@m01 ~]# ansible --version
    ansible 2.9.10
    config file = /etc/ansible/ansible.cfg
    configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
    ansible python module location = /usr/lib/python2.7/site-packages/ansible
    executable location = /usr/bin/ansible
    python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]

    4.Ansible配置文件读取顺序

    [root@m01 ~]# vim /etc/ansible/ansible.cfg 
    # nearly all parameters can be overridden in ansible-playbook
    # or with command line flags. ansible will read ANSIBLE_CONFIG,
    # ansible.cfg in the current working directory, .ansible.cfg in
    # the home directory or /etc/ansible/ansible.cfg, whichever it
    # finds first

    [root@m01 ~]# rpm -ql ansible
    [root@m01 ~]# zcat /usr/share/man/man1/ansible-config.1.gz

    #要查看完整列表,请访问https://docs.ansibe.com/或使用ansibe-config命令。
    For a full list check fI\%https://docs.ansible.com/fP&. or use the fIansible-configfP command.

    #/etc/ansible/ansible.cfg 配置文件,如果存在则使用
    /etc/ansible/ansible.cfg -- Config file, used if present

    #~/.ansible.cfg 用户配置文件,覆盖默认配置(如果存在)
    ~/.ansible.cfg -- User config file, overrides the default config if present

    #&/ansible.cfg 本地配置文件(在当前工作目录中)假定为(aqproject-specific)(aq,如果存在,则重写其余文件)。
    &./ansible.cfg -- Local config file (in current working directory) assumed to be (aqproject specific(aq and overrides the rest if present.

    #如上所述,ANSIBLE_CONFIG环境变量将覆盖所有其他环境变量。
    As mentioned above, the ANSIBLE_CONFIG environment variable will override all others.

    #生效优先级
    ANSIBLE_CONFIG >>  $ANSIBLE_CONFIG/ansible.cfg >> ~/.ansible.cfg >> /etc/ansible/ansible.cfg

    5.配置Ansible

    [root@m01 ~]# cat /etc/ansible/ansible.cfg 
    #inventory     = /etc/ansible/hosts     #主机列表配置文件
    #library       = /usr/share/my_modules/ #库文件存放目录
    #remote_tmp     = ~/.ansible/tmp         #临时py文件存放在远程主机目录
    #local_tmp     = ~/.ansible/tmp         #本机的临时执行目录
    #forks         = 5                       #默认并发数
    #sudo_user     = root                   #默认sudo用户
    #ask_sudo_pass = True                     #每次执行是否询问sudo的ssh密码
    #ask_pass     = True                     #每次执行是否询问ssh密码
    #remote_port   = 22                     #远程主机端口
    host_key_checking = False                 #跳过检查主机指纹
    log_path = /var/log/ansible.log           #ansible日志

    #普通用户提权操作
    [privilege_escalation]
    #become=True
    #become_method=sudo
    #become_user=root
    #become_ask_pass=False

     

    四、配置主机清单

    1.单主机配置

    1)方式一:
    #ip+端口+用户+密码
    [root@m01 ~]# vim /etc/ansible/hosts
    [web01]
    172.16.1.7 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='1'
    [web03]
    172.16.1.7 ansible_ssh_port=22

    #测试主机清单
    [root@m01 ~]# ansible '*' -m ping
    2)方式二
    [root@m01 ~]# vim /etc/hosts
    172.16.1.7 web01
    172.16.1.9 web03

    [root@m01 ~]# vim /etc/ansible/hosts
    [web01]
    web01 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='1'
    [web03]
    web03 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='1'
    3)方式三
    [root@m01 ~]# vim /etc/ansible/hosts 
    [web1]
    web01
    [web3]
    web03
    [web1:vars]
    ansible_ssh_pass='1'
    [web3:vars]
    ansible_ssh_pass='1'
    4)基于秘钥的方式
    #生成密钥对
    [root@m01 ~]# ssh-keygen

    #推送秘钥
    [root@m01 ~]# ssh-copy-id 172.16.1.7
    [root@m01 ~]# ssh-copy-id 172.16.1.9

    #配置
    [root@m01 ~]# vim /etc/ansible/hosts
    [web1]
    web01
    [web3]
    web03

    2.主机组配置

    [root@m01 ~]# vim /etc/ansible/hosts 
    [web_group]
    web01
    web03
    [nfs_group]
    nfs ansible_ssh_pass='1'

    #查看组下面的机器
    [root@m01 ~]# ansible 'web_group' --list-host
    hosts (2):
      web01
      web03

    3.定义多组操作

    1)操作多个组
    [root@m01 ~]# ansible 'web_group,nfs_group' -m ping
    2)定义包含组
    [root@m01 ~]# vim /etc/ansible/hosts 
    [web_group]
    web01
    web03

    [nfs_group]
    nfs ansible_ssh_pass='1'

    [mysql_group]
    db01 ansible_ssh_pass='1'
    db02 ansible_ssh_pass='1'

    [nfs_zu:children]
    web_group
    nfs_group

    #注意:
    主机名和组名称不要一样,否则执行命令时不知道找主机还是主机组

    五、ad-hoc概述

    1.什么是ad-hoc

    ad-hoc简而言之就是远程执行“临时命令”,执行完即结束,并不会保存

    2.ad-hoc使用场景

    比如在多台机器上查看某个进程是否启动,或拷贝指定文件到本地,等等

    3.ad-hoc使用

    img

    [root@m01 ~]# ansible 'web01' -m shell -a 'free -m'
    web01 | CHANGED | rc=0 >>
                total       used       free     shared buff/cache   available
    Mem:            972         110         461          19         400         667
    Swap:          2047           0        2047

    4.ad-hoc返回结果颜色含义

    绿色: 代表被管理端主机没有被修改
    黄色: 代表被管理端主机发现变更
    红色: 代表出现了故障,注意查看提示
    紫色:警告

    5.ad-hoc常用模块

    command             # 执行shell命令(不支持管道等特殊字符)
    shell               # 执行shell命令
    script              # 执行shell脚本
    yum_repository      # 配置yum仓库
    yum                 # 安装软件
    copy                # 变更配置文件
    file                # 建立目录或文件
    service             # 启动与停止服务
    mount               # 挂载设备
    cron                # 定时任务
    get_url             # 下载软件
    firewalld           # 防火墙
    selinux             # selinux

    6.ad-hoc帮助

    #查看所有模块
    [root@m01 ~]# ansible-doc -l

    #常看指定模块使用方法
    [root@m01 ~]# ansible-doc command
    EXAMPLES:

    #查看模块可以使用的参数
    [root@m01 ~]# ansible-doc -s file

    六、Ansible命令模块

    1.command模块

    [root@m01 ~]# ansible 'web01' -m command -a 'free -m'
    web01 | CHANGED | rc=0 >>
                total       used       free     shared buff/cache   available
    Mem:            972         110         460          19         401         667
    Swap:          2047           0        2047

    #command命令不支持特殊符号
    [root@m01 ~]# ansible 'web01' -m command -a "ifconfig eth0 | awk 'NR==2 {print $2}'"
    web01 | FAILED | rc=1 >>
    |: Unknown host
    ifconfig: `--help' gives usage information.non-zero return code

    #当ansible命令没指定模块时,默认使用command模块

    2.shell模块

    #shell模块识别特殊符号,但是不支持 $符
    [root@m01 ~]# ansible 'web01' -m shell -a "ifconfig eth0 | awk 'NR==2 {print $2}'"
    web01 | CHANGED | rc=0 >>
          inet 10.0.0.7 netmask 255.255.255.0 broadcast 10.0.0.255

    #可以使用 撬棍 转义 $符,就可以识别了
    [root@m01 ~]# ansible 'web01' -m shell -a "ifconfig eth0 | awk 'NR==2 {print $2}'"
    web01 | CHANGED | rc=0 >>
    10.0.0.7

    3.script模块

    [root@m01 ~]# ansible 'web_group' -m script -a '/root/mkdir.sh'
    web03 | CHANGED => {
       "changed": true,
       "rc": 0,
       "stderr": "Shared connection to web03 closed. ",
       "stderr_lines": [
           "Shared connection to web03 closed."
      ],
       "stdout": "",
       "stdout_lines": []
    }
    web01 | CHANGED => {
       "changed": true,
       "rc": 0,
       "stderr": "Shared connection to web01 closed. ",
       "stderr_lines": [
           "Shared connection to web01 closed."
      ],
       "stdout": "",
       "stdout_lines": []
    }

    #验证文件
    [root@m01 ~]# ansible 'web_group' -m shell -a 'ls -ld /123'
    web01 | CHANGED | rc=0 >>
    drwxr-xr-x 2 root root 6 Sep 17 17:26 /123
    web03 | CHANGED | rc=0 >>
    drwxr-xr-x 2 root root 6 Sep 17 17:26 /123

    七、Ansible软件管理模块

    yum_repository      # 配置yum仓库
    yum                 # 安装软件

    1. yum_repository 模块

    [root@m01 ~]# ansible-doc yum_repository
    EXAMPLES:
    yum_repository:
      name: epel
      description: EPEL YUM repo
      baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
      file: external_repos
      gpgcheck: no
      mirrorlist: http://mirrorlist.repoforge.org/el7/mirrors-rpmforge
      enabled: no
      state: absent
       
    [nginx-stable]
    name=nginx stable repo
    baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
    gpgcheck=1
    enabled=1
    gpgkey=https://nginx.org/keys/nginx_signing.key
    module_hotfixes=true

    #创建nginx官方源
    [root@m01 ~]# ansible 'web_group' -m yum_repository -a 'name="nginx-stable" description="nginx stable repo" baseurl=http://nginx.org/packages/centos/7/$basearch/ gpgcheck=no enabled=yes file=nginx'

    #添加源:不修改 file,只要name不相同就是添加源
    [root@m01 ~]# ansible 'web_group' -m yum_repository -a 'name="nginx-mainline" description="nginx mainline repo" baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/ gpgcheck=no enabled=yes file=nginx'

    #修改源:不修改 file 和 name,改其他的内容都会修改源
    [root@m01 ~]# ansible 'web_group' -m yum_repository -a 'name="nginx-mainline" description="nginx mainline repo" baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/ gpgcheck=no enabled=yes file=nginx'

      name: #yum源 []里面的内容
      description: #yum源 name的值
      baseurl: #yum源 中的仓库地址
      file: #yum源的名字
      gpgcheck: #yum源是否检查
      mirrorlist: #源的列表
      enabled: no #源是否启动
      state:
      absent #删除
      present #添加

    2.yum模块

    1)语法帮助
    [root@m01 ~]# ansible-doc yum
    EXAMPLES:
    - name: install the latest version of Apache
    yum:
      name: httpd
      state: latest

    name:
    httpd #服务的名字
    http:// #软件包网上的地址
    /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm #本地的rpm包
    state:
    latest #安装最新的版本
    present #安装
    absent #卸载
    2)yum实例
    #名字安装httpd
    [root@m01 ~]# ansible 'web_group' -m yum -a 'name=httpd state=present'
    #类似于在远程机器上执行 yum install -y httpd

    #使用网上软件包安装
    1.找到网上的包
    https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.1-1.el7.x86_64.rpm
    2.安装
    [root@m01 ~]# ansible 'web_group' -m yum -a 'name=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.1-1.el7.x86_64.rpm state=present'
    #类似于在远程机器上执行 yum install -y https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.1-1.el7.x86_64.rpm

    #使用本地包安装
    1.上传包(上传到web端)
    2.安装
    [root@m01 ~]# ansible 'web_group' -m yum -a 'name=/tmp/nginx-1.16.1-1.el7.ngx.x86_64.rpm state=present'
    #类似于在远程机器上执行 yum localinstall -y /tmp/nginx-1.16.1-1.el7.ngx.x86_64.rpm

    八、文件管理模块

    copy                # 变更配置文件
    file                # 建立目录或文件
    get_url             # 下载软件

    1.copy模块

    1)帮助语法
    [root@m01 ~]# ansible-doc copy
    EXAMPLES:
    - name: Copy file with owner and permissions
    copy:
      src: /srv/myfiles/foo.conf
      dest: /etc/foo.conf
      owner: foo
      group: foo
      mode: '0644'
      backup: yes
      follow: yes
      content: '# This file was moved to /etc/other.conf'
       
    src: #源路径(要进行copy的文件,文件在控制端)
    dest: #目标路径(在受控端)
    owner: #文件推过去之后的属主
    group: #文件推过去之后的属组
    mode: #文件推过去之后的权限
    backup: #文件件是否备份
    yes #备份
    no #不备份
    follow: #是否识别软链接
    yes
    no
    content: #直接写入内容到文件
    2)模块实例
    #推送nginx官方源
    [root@m01 ~]# ansible 'web_group' -m copy -a 'src=/etc/yum.repos.d/nginx.repo dest=/etc/yum.repos.d/'

    #推送文件并授权
    [root@m01 ~]# ansible 'web_group' -m copy -a 'src=/root/test.conf dest=/etc/nginx/conf.d/ owner=root group=root mode=777'

    #推送文件并备份
    [root@m01 ~]# ansible 'web_group' -m copy -a 'src=/code/index.html dest=/code owner=nginx group=nginx mode=0644 backup=yes'

    #识别软链接
    [root@m01 ~]# ansible 'web_group' -m copy -a 'src=/root/test dest=/tmp owner=nginx group=nginx mode=0644 follow=yes'
    [root@m01 ~]# ansible 'web_group' -m copy -a 'src=/root/test dest=/tmp owner=nginx group=nginx mode=0644 follow=no'

    #直接写入内容到文件
    [root@m01 ~]# ansible 'web_group' -m copy -a 'content="123456" dest=/etc/rsync_password mode=0600'

    2.file模块

    1)帮助语法
    [root@m01 ~]# ansible-doc file
    EXAMPLES:
    - name: Change file ownership, group and permissions
    file:
      path: /etc/foo.conf
      owner: foo
      group: foo
      mode: '0644'
      state: link,hard,touch,directory,absent
      recurse: yes

    src: #源文件(如果做软链接就是远程机器上的文件)
    dest: #目标文件(如果做软链接就是远程机器上的链接文件)
    path: #路径/文件
    owner: #文件或目录的属主
    group: #文件或目录的属组
    mode: #文件或目录的权限
    state:
    link #软链接
    touch #创建文件
    directory #创建目录
    absent #删除
    recurse: #递归操作
    yes
    2)file模块实践
    1.创建目录
    [root@m01 ~]# ansible 'web_group' -m file -a 'path=/code state=directory'
    #相当于到远程机器 mkdir /code

    2.创建目录并授权
    [root@m01 ~]# ansible 'web01' -m file -a 'path=/code state=directory owner=nginx group=nginx mode=755'
    #相当于执行 mkdir /code && chown -R nginx.nginx /code && chmod 755 /code

    3.递归创建目录
    [root@m01 ~]# ansible 'web01' -m file -a 'path=/code/wordpress/wp-content/uploads state=directory owner=nginx group=nginx mode=755'
    1)如果目录不存在则创建并递归授权
    2)如果目录上级存在,则只授权新创建的目录

    4.递归授权目录
    [root@m01 ~]# ansible 'web01' -m file -a 'path=/code state=directory owner=nginx group=nginx mode=755 recurse=yes'

    5.创建文件
    [root@m01 ~]# ansible 'web01' -m file -a 'path=/code/1.txt state=touch owner=nginx group=nginx mode=666'

    6.删除文件
    [root@m01 ~]# ansible 'web01' -m file -a 'path=/code/index.html state=absent'

    7.做软连接
    [root@m01 ~]# ansible 'web01' -m file -a 'src=/code/wordpress dest=/code/link state=link'

    #注意:
    1.创建文件时,上层目录必须存在

    3. get_url 模块

    1)帮助语法
    [root@m01 ~]# ansible-doc get_url
    EXAMPLES:
    - name: Download foo.conf
    get_url:
      url: http://example.com/path/file.conf
      dest: /etc/foo.conf
      mode: '0440'
      checksum:
      sha256:http://example.com/path/sha256sum.txt
     
    url: #下载文件的地址
    dest: #下载保存的路径
    mode: #下载之后的权限
    checksum: #下载时进行验证
    sha256:http://example.com/path/sha256sum.txt
    md5
    2)模块实例
    #下载包
    [root@m01 ~]# ansible 'web_group' -m get_url -a 'url=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-2.el7.noarch.rpm dest=/tmp/'

    #下载包并授权
    [root@m01 ~]# ansible 'web_group' -m get_url -a 'url=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-2.el7.noarch.rpm dest=/tmp/ mode=777'

    #下载包时验证
    [root@linux /code]# md5sum index.html
    ba1f2511fc30423bdbb183fe33f3dd0f index.html

    [root@m01 ~]# ansible 'web03' -m get_url -a 'url=http://10.0.0.7/index.html dest=/tmp mode=777 checksum=md5:ba1f2511fc30423bdbb183fe33f3dd0f'

     

  • 相关阅读:
    便携版Mysql安装
    Markdown 语法学习
    布局页中的特殊情况(比如说只有某页有的banner)
    Jsp Layout 布局页
    eclipse变量名自动补全
    java中的final关键字(2013-10-11-163 写的日志迁移
    java的重载(overload) (2013-10-11-163 写的日志迁移
    java 的多态(2013-10-11-163 写的日志迁移
    java中类与对象的概念(2013-05-04-bd 写的日志迁移
    java的一些相关介绍(2013-10-07-163 写的日志迁移
  • 原文地址:https://www.cnblogs.com/jhno1/p/13687565.html
Copyright © 2011-2022 走看看