Ansible

Ansible简介

  • ansible是一种基于python语言开发的轻量级自动化运维工具,它可以自动化批量完成主机服务配置管理,软件部署,执行特定命令等工作

  • ansible的核心组件有ansible core(核心代码),host inventory(要管理的主机),core modules(核心模块),custom modules(用户可以自定义模块),playbook (yaml, jinjia2),connect plugin(paramiko)

Ansible的安装和基础配置

Summary     : SSH-based configuration management, deployment, and task execution system
URL         : http://ansible.com
License     : GPLv3+
Description :         需要配置好epelYUM源
            : Ansible is a radically simple model-driven configuration management,
            : multi-node deployment, and remote task execution system. Ansible works
            : over SSH and does not require any software or daemons to be installed
            : on remote nodes. Extension modules can be written in any language and
            : are transferred to managed machines automatically.
[root@centos ~]# yum install ansible -y  自动安装yaml,jinjia2,paramiko等相关库
,,,,,,,
Complete!
[root@centos ~]# ansible --version  测试是否安装成功,提示有ansible版本号
ansible 2.1.2.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
[root@centos ~]# ssh-keygen 基于秘钥对管理client
[root@centos ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.40.138
[root@centos ~]# ssh root@192.168.40.138  "ifconfig>/dev/null"  测试是否能够免密码登录client,我这里只有一台client
[root@centos ~]#
[root@centos ansible]# vim /etc/ansible/hosts 定义client
[singleclient]  被管主机的定义方式,该配置文件有详细范例
192.168.40.138
[root@centos ansible]# ansible all  -m ping   需要关闭client的selinux
192.168.40.138 | SUCCESS => {
    "changed": false, 
    "ping": "pong"     测试能ping通
}

Ansible常用命令的使用

 ansible <host-pattern主机列表> [-m module_name模块名字] [-a args模块参数] [options]
 常用[options] 更多参数需要man ansible 或 ansible --help了解
 
 -C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur 预测结果
 -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check 
 -e EXTRA_VARS, --extra-vars=EXTRA_VARS 向playbook里传递变量
                        set additional variables as key=value or YAML/JSON
 -f FORKS, --forks=FORKS 多少个线程并行执行任务
                        specify number of parallel processes to use
                        
 ansible-doc - show documentation on Ansible modules
 ansible-doc -l 列出所有可用模块 ansible-doc -s module 查看某个模块用法
 
 ansible-playbook - run an ansible playbook 运行剧本内的编排任务

Ansible的playbook编写

  • playbook的主要组成部分Tasks(由多个模块组成的多个任务),Variables(变量),Template(模版针对服务配置文件),Handler(处理器),Roles(角色)

  • playbook一定要指定Hosts(主机),Users(以哪个用户身份执行任务)

  • playbook遵循YAML语言语法格式,常用的有序列用“-”表示;key:value键值对;{k1:v1,k2:v2}字典等

  • 下面为playbook由tasks,variables,template,handler,roles逐个测试,当然可以组合使用,组合使用才能发挥playbook的任务编排能力

[root@centos ~]# ansible-playbook ./test1.yml  --syntax-check
playbook: ./test1.yml
[root@centos ~]# cat test1.yml 
- hosts: singleclient 指定要在那些主机上运行playbook
  remote_user: root  指定了以那个用户身份去运行playbook
  tasks:
  - name: install httpd 任务一
    yum: name=httpd state=present
  - name: start the httpd service 任务二
    service: name=httpd state=running
  - name: reporting 任务三
    shell: /bin/echo "httpd installed and running"
  ignore_errors: true  如果在运行任务三时报错,就忽略掉报错
[root@centos ~]# ansible-playbook ./test1.yml 
PLAY [singleclient] ************************************************************
其中- host是顶级层是个大列表,remote_user,tasks和ignore_errors是顶级层的元素,
remote_user和tasks都是键值对,tasks的值比较特殊,为三个列表;playbook中可以有多个- host
ansible的变量分为fact变量就是ansible all -m setup获得的变量
通过--extra-var 参数传进playbook的变量,playbook 中通过{{}}引用变量 例如:
yum: name={{software}} state=present 也可以在playbook中通过var关键字来定义并引用
ansible-doc --extra-var "sotfware=nginx" test1.yml 则会安装nginx
inventory的主机变量和组变量,在主机后面加上k=v ,playbook通过{{k}}来引用,模版则会针对不同的主机得到不同的值
[root@centos ~]# cat index.txt /template/index.j2 
just test port for {{ port }} 源文件
just test a port {{ port }} 模版文件
[root@centos ~]# cat test3.yml 
- hosts: singleclient
  remote_user: root
  tasks: 此处为简单测试,实际生产环境会针对服务的配置文件来操作
  - name: copy configuration file
    copy: src=/root/index.txt dest=/tmp/index.txt 复制源文档到client
  - name: modify configuration file
    template: src=/template/index.j2 dest=/tmp/index.txt 根据模版修改client的index.txt文档
[root@centos ~]# grep "port" /etc/ansible/hosts 
192.168.40.138 port=888  主机变量 port
#port=888
[root@centos ~]# ssh root@192.168.40.138 "cat /tmp/index.txt"
just test a port 888
[root@centos ~]# grep  -C2 "singleclient" /etc/ansible/hosts 
## 192.168.100.1
## 192.168.100.10
[singleclient]采用组变量方式,40.138,40.200都会相同的变量,其值也相同
192.168.40.138 
192.168.40.200
[singleclient:vars]
port=888
# Ex 2: A collection of hosts belonging to the 'webservers' group
[root@centos ~]# ansible-playbook test3.yml  test3.yml仍能正常执行
PLAY [singleclient] ************************************************************
[root@centos ~]# ssh root@192.168.40.138 "cat /tmp/index.txt"
just test a port 888   测试结果和主机变量测试结果相同
ansible的条件,迭代和处理器测试
tasks: 当client主机发行版为CentOS时,才会关机
  - name: "shut down CentOS 6 systems"   
    command: /sbin/shutdown -t now  
    when:
    - ansible_distribution == "CentOS"
[root@centos ~]# ansible-playbook test4.yml 
PLAY [singleclient] ************************************************************
TASK [setup] *******************************************************************
ok: [192.168.40.138]
TASK [copy wrong file to test when] ********************************************
fatal: [192.168.40.138]: FAILED! => {"failed": true, "msg": "the file_name 
...ignoring
TASK [ping test] ***************************************************************
ok: [192.168.40.138]
PLAY RECAP *********************************************************************
192.168.40.138             : ok=3    changed=0    unreachable=0    failed=0   
[root@centos ~]# cat test4.yml 
- hosts: singleclient
  remote_user: root
  tasks:
  - name: copy wrong file to test when
    copy: src=/root/index dest=/tmp/index.txt
    register: result
    ignore_errors: True 为了不影响下一条任务执行和when条件判断
  - name: ping test
    ping: 
    when: result|failed  上一条命令执行失败时,才执行ping
,,,,,,,,,,,,,,,,,
- name: add several users  user: name={{ item }} state=present groups=wheel 迭代测试 
 with_items: 
     - testuser1 
     - testuser2
,,,,,,,,,,,,,,,,,    
tasks:处理器测试
  - name: ensure apache is at the latest version
    yum: name=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
ansible的roles使用
roles是变量,任务,文件,模版,处理器,分别放在单独的目录并都是role目录的子目录
role目录会有site.yml为ansible-playbook的执行入口,需要相应的文件是会自动导入
适用场景当有大量主机要安装配置不同的服务时,比如20台主机需要安装配置nginx,
其他20台需要安装配置mysql,则可以新建nginx和mysql的role来执行安装配置nginx和mysql服务

role内各目录中可用的文件

tasks目录:至少应该包含一个名为main.yml(只写任务列表)的文件,其定义了此角色的任务列表

files目录:存放由copy或script等模块调用的文件; 

templates目录:template模块会自动在此目录中寻找Jinja2模板文件; 

handlers目录:此目录中应当包含一个main.yml(只写handler)文件,用于定义此角色用到的各handler;

vars目录:应当包含一个main.yml(只写变量),用于定义此角色用到的变量;

meta目录:应当包含一个main.yml文件,用于定义此角色的特殊设定及其依赖关系;

default目录:为当前角色设定默认变量时使用此目录;应当包含一个main.yml文件;

roles目录的同级目录下需要新建site.yml 来作为ansible-playbook的执行入口,定义Hosts和Users
使用roles关键字来指定执行roles目录下的哪个role中的编排任务

通过以上总结可以对ansible的简单使用加深理解,ansible的其他用法需要参考官网或其他文档

原创文章,作者:Snoo,如若转载,请注明出处:http://www.178linux.com/57466

(0)
SnooSnoo
上一篇 2016-11-14 08:27
下一篇 2016-11-14 08:28

相关推荐

  • 从增删改查角度学习linux基础命令

    从增删改查角度学习linux基础命令   本文从文件的增加、删除、修改、查询四个角度介绍linux的基本命令,介绍如下:   一.增 touch命令是最常用的创建文件的命令,它的常见参数如下: -a 或–time=atime或–time=access或–time=use  只更改存取时间。 -c 或&#…

    2017-07-15
  • Docker 实例

    1、Docker 安装 Nginx 方法一:通过 Dockerfile构建 创建Dockerfile 首先,创建目录nginx,用于存放后面的相关东西。 # mkdir -p nginx/www nginx/logs nginx/conf www目录将映射为nginx容器配置的虚拟目录 logs目录将映射为nginx容器的日志目录 conf目录里的配置文件将…

    2018-01-22
  • 细节决定成败–空格的巨大作用以及正则表达式中元字符的转义

    字符串的条件判定 1.字符串判定 一定要用双[[ ]] 2.字符串判定=~默认支持扩展正则表达式,这里注意双引号的使用 仅仅做是否包含时,有无双引号无区别。 但是利用其他扩展表达式时 双引号一定要去掉 锚定示例 多条件判定时-o -a使用时,不能使用双中括号 空格有无的差别 !的使用细节 !到目前为止 有两种意义 条件判定取反 历史命令的调用 两者的使用却别…

    2017-03-19
  • $@与$*的不同之处

    $@与$*的不同之处 $*: 把我们传递给脚本的参数全部合为一个字节,当成一个字符串或者参数来使用。 $@: 把我们传递给脚本的所有参数,每个参数都为独立字符串,当我们用 \((n) 来调用的时候, 输入参数的位置为第几个,那我们就用用\)n来调用第几个,一对应。 下面我们用代码来看一下这两个的区别: 创建一个简单的脚本让他输出我们输入的多个参数:&#822…

    2017-06-06
  • 第二周作业

    1、Linux上的文件管理类命令都有哪些,其常用的使用方法及其相关示例演示。  cp复制,mv移动,rm删除     1、cp:             1,用法:      &n…

    Linux干货 2016-07-04
  • N25第二周视频作业:用户、组与权限管理详解

    此篇博客是根据视频要求写的,因为马哥在视频中说了,用户组、权限在linux运维过程中比较重要,所以一定要深入学习 首先,先介绍一下用户、组与权限是什么:     用户:用户时指你在服务器上的标识,通过不同类型的用户,你享受到不同的待遇,而待遇就是权限的大小。每个用户在服务器上都有唯一的id标识,即使你将此用户删除,再建…

    Linux干货 2016-11-26