ansible详解

ansible:

   特性:

    模块化,调用特定的模块来完成特定任务;

    基于Python语言实现,由Paramiko,PyYAML和Jinja2三个关键模块实现;

    部署简单,agentless;

    主从模式;

    支持自定义模块;

    支持playbook

  (支持幂等性)

   组成部分:

    ansible core

    host inventory

    connection plugins

    modules:

        custom modules;

        core modules;

    playbooks

   配置文件:

    主配置文件:/etc/ansible/ansible.cfg

    Host Inventory:/etc/ansible/hosts

    

ansible命令:

     ansible  <host-pattern>  [-f forks]  [-m module_name]  [-a args]

-i PATH, --inventory=PATH:指明使用的host inventory文件路径;


注:在使用ansible命令在director主机上统一管控后端集群主机时,director基于ssh协议与后端主机进行管控,所以要提前生成director的密钥对copy给集群中需要被ansible管控的主机,使director主机与集群中的主机可以基于密钥对方式连接ssh。


在director主机中安装ansible:

[root@localhost ~]# yum install ansible
[root@localhost ~]# vim /etc/ansible/hosts   #在hosts文件中定义要管控的主机
[websrvs]
172.16.61.2
172.16.61.3
...

 

常用模块:

[-a args]:

args: key=value  键值类型

       

    ①command:默认模块:在远程节点上运行一个命令;

-a 'COMMAND'

   注:command模块的参数非为kv格式,而是直接给出要执行的命令即可;

[root@localhost ~]# ansible all -m command -a 'ls'  #在远程节点上运行ls命令
172.16.61.2 | success | rc=0 >>
anaconda-ks.cfg

172.16.61.3 | success | rc=0 >>
anaconda-ks.cfg

[root@localhost ~]# ansible all -a 'ls'      #command为默认模块不-m指明也能默认使用
172.16.61.3 | success | rc=0 >>
anaconda-ks.cfg

172.16.61.2 | success | rc=0 >>
anaconda-ks.cfg

    ②user:

-a 'name=  state={present|absent}  force=   system=  uid=  shell=  home='

[root@localhost ~]# ansible websrvs -m user -a 'name=tz state=present'  #在远程节点创建该用户
172.16.61.3 | success >> {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1001, 
    "home": "/home/tz", 
    "name": "tz", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}

172.16.61.2 | success >> {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1001, 
    "home": "/home/tz", 
    "name": "tz", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}

[root@localhost ~]# ansible websrvs -m user -a 'name=tz state=absent force=true' #删除该用户及家目录
172.16.61.3 | success >> {
    "changed": true, 
    "force": true, 
    "name": "tz", 
    "remove": false, 
    "state": "absent"
}

172.16.61.2 | success >> {
    "changed": true, 
    "force": true, 
    "name": "tz", 
    "remove": false, 
    "state": "absent"
}


    ③group:

 -a 'name=  state={present|absent}  gid=  system='

[root@localhost ~]# ansible websrvs -m group -a 'name=grp state=present system=true' #创建grp系统组
172.16.61.2 | success >> {
    "changed": true, 
    "gid": 992, 
    "name": "grp", 
    "state": "present", 
    "system": true
}

172.16.61.3 | success >> {
    "changed": true, 
    "gid": 992, 
    "name": "grp", 
    "state": "present", 
    "system": true
}

    ④cron:

-a 'name=  state=  minute=  hour=  day=  month=  weekday=  job='

[root@localhost ~]# ansible websrvs -m cron -a "name=timesync minute='*/5' job='/usr/sbin/ntpdate 172.16.0.1 &> /dev/null'"   #在远程节点上定义周期性任务,每五分钟执行一次同步时间的操作
172.16.61.3 | success >> {
    "changed": true, 
    "jobs": [
        "timesync"
    ]
}

172.16.61.2 | success >> {
    "changed": true, 
    "jobs": [
        "timesync"
    ]
}

[root@localhost ~]# crontab -l    #远程节点上可以查看出该周期任务。
#Ansible: timesync
*/5 * * * * /usr/sbin/ntpdate 172.16.0.1 &> /dev/null

[root@localhost ~]# ansible websrvs -m cron -a "name=timesync state=absent"  #删除该周期性任务
172.16.61.3 | success >> {
    "changed": true, 
    "jobs": []
}

172.16.61.2 | success >> {
    "changed": true, 
    "jobs": []
}


    ⑤ping:

没有参数

[root@localhost ~]# ansible websrvs -m ping 
172.16.61.3 | success >> {
    "changed": false, 
    "ping": "pong"
}

172.16.61.2 | success >> {
    "changed": false, 
    "ping": "pong"
}

    ⑥file:

-a 'path=  mode=  owner=  group=  state={file|directory|link|hard|touch|absent}  src='

[root@localhost ~]# ansible websrvs -m file -a 'path=/tmp/test state=touch mode=600'  #在远程节点上/tmp目录下创建权限为600,名称为test的文件
172.16.61.3 | success >> {
    "changed": true, 
    "dest": "/tmp/test", 
    "gid": 0, 
    "group": "root", 
    "mode": "0600", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}

172.16.61.2 | success >> {
    "changed": true, 
    "dest": "/tmp/test", 
    "gid": 0, 
    "group": "root", 
    "mode": "0600", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@localhost ~]# ansible websrvs -m file -a 'path=/tmp/test state=absent' #删除该文件
172.16.61.3 | success >> {
    "changed": true, 
    "path": "/tmp/test", 
    "state": "absent"
}

172.16.61.2 | success >> {
    "changed": true, 
    "path": "/tmp/test", 
    "state": "absent"
}
[root@localhost ~]# ansible websrvs -m file -a 'path=/tmp/test state=link src=/etc/fstab' #在远程节点上创建/etc/fstab的符号链接指向/tmp/test
172.16.61.3 | success >> {
    "changed": true, 
    "dest": "/tmp/test", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    "size": 10, 
    "src": "/etc/fstab", 
    "state": "link", 
    "uid": 0
}

172.16.61.2 | success >> {
    "changed": true, 
    "dest": "/tmp/test", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    "size": 10, 
    "src": "/etc/fstab", 
    "state": "link", 
    "uid": 0
}


    ⑦copy:把管理端的文件给远程节点各复制一份

-a 'dest=  src=\'#\'"  owner=  group=  mode='

[root@localhost ~]# ansible websrvs -m copy -a 'src=/etc/fstab dest=/tmp/fstab mode=660' #将本地主机/etc/fstab文件复制到远程节点的/tmp目录下,权限为660
172.16.61.3 | success >> {
    "changed": true, 
    "checksum": "37ed7ee7a0cb241d01cf18351d2c541d12003937", 
    "dest": "/tmp/fstab", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8c466190fc6993d65baeeb0beff52de4", 
    "mode": "0660", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 619, 
    "src": "/root/.ansible/tmp/ansible-tmp-1454251002.67-64682182817600/source", 
    "state": "file", 
    "uid": 0
}

172.16.61.2 | success >> {
    "changed": true, 
    "checksum": "37ed7ee7a0cb241d01cf18351d2c541d12003937", 
    "dest": "/tmp/fstab", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8c466190fc6993d65baeeb0beff52de4", 
    "mode": "0660", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 619, 
    "src": "/root/.ansible/tmp/ansible-tmp-1454251002.66-162169360284592/source", 
    "state": "file", 
    "uid": 0
}


    ⑧yum:

-a 'name=  conf_file=  state={present|latest|absent}  enablerepo= disablerepo='

[root@localhost ~]# ansible websrvs -m yum -a 'name=httpd state=present'  #在远程节点上安装httpd程序
172.16.61.2 | success >> {
    "changed": false, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "httpd-2.4.6-31.el7.centos.x86_64 providing httpd is already installed" #提示已经被安装了
    ]
}

172.16.61.3 | success >> {
    "changed": false, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "httpd-2.4.6-31.el7.centos.x86_64 providing httpd is already installed"
    ]
}

     

    ⑨service:启动远程节点的服务

      -a  'name=  state={started|stopped|restarted}  enabled=  runlevel='

[root@localhost ~]# ansible websrvs -m service -a 'name=httpd state=started enabled=true' #开启远程节点的httpd服务,并且设定开机启动 
172.16.61.2 | success >> {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started"
}

172.16.61.3 | success >> {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started"
}


    ⑩shell:在shell环境中运行命令

      -a  'COMMAND'

[root@localhost ~]# ansible websrvs -m shell -a 'echo "tianzhuang" | passwd --stdin user1'
172.16.61.3 | success | rc=0 >>
Changing password for user user1.
passwd: all authentication tokens updated successfully.

172.16.61.2 | success | rc=0 >>
Changing password for user user1.
passwd: all authentication tokens updated successfully.

     

            

            script:将主机上的脚本复制到远程节点上并运行

    -a  '/PATH/TO/SCRIPT'

[root@localhost ~]# vim hello.sh  #在本地创建一个脚本

#!/bin/bash
echo "hello"

[root@localhost ~]# ansible websrvs -m script -a '/root/hello.sh' #在远程节点上运行该脚本
172.16.61.2 | success >> {
    "changed": true, 
    "rc": 0, 
    "stderr": "OpenSSH_6.6.1, OpenSSL 1.0.1e-fips 11 Feb 2013\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 56: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug1: mux_client_request_session: master session id: 2\r\nShared connection to 172.16.61.2 closed.\r\n", 
    "stdout": "hello\r\n"
}

172.16.61.3 | success >> {
    "changed": true, 
    "rc": 0, 
    "stderr": "OpenSSH_6.6.1, OpenSSL 1.0.1e-fips 11 Feb 2013\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 56: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug1: mux_client_request_session: master session id: 2\r\nShared connection to 172.16.61.3 closed.\r\n", 
    "stdout": "hello\r\n"
}

                    setup:

   获取指定主机的facts;


       注: ansible-doc命令:获取模块列表,及模块使用格式;

 ansible-doc  -l

     ansible-doc  -s  module_name

 

ansible playbooks:

 核心元素:

    Tasks

    Variables

    Templates

    Handlers

    Roles

  组织格式:YAML

       

    列表:-

    字典:k:v数据,键值对

[root@localhost ~]# vim first.yml

- hosts: websrvs
  remote_user: root
  tasks:
  - name: install httpd
    yum: name=httpd state=present
  - name: install php
    yum: name=php state=present
  - name: start httpd
    service: name=httpd state=started

  

ansible-playbook命令:

     ansible-playbook  <filename.yml> ...  [options]

[root@localhost ~]# ansible-playbook first.yml

PLAY [websrvs] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [172.16.61.3]
ok: [172.16.61.2]

TASK: [install httpd] ********************************************************* 
ok: [172.16.61.3]
ok: [172.16.61.2]

TASK: [install php] *********************************************************** 
changed: [172.16.61.3]
changed: [172.16.61.2]

TASK: [start httpd] *********************************************************** 
ok: [172.16.61.2]
ok: [172.16.61.3]

PLAY RECAP ******************************************************************** 
172.16.61.2                : ok=4    changed=1    unreachable=0    failed=0   
172.16.61.3                : ok=4    changed=1    unreachable=0    failed=0



playbook的元素:

(1)变量:

     变量命名:字母、数字和下划线组成,仅能以字母开头;

  变量种类:

     ①facts:由远程主机发回的主机属性信息,这些信息被保存在ansible变量中;无须定义,可直接调用;

     ②自定义变量:

   通过命令行传递: ansible-playbook  test.yml  --extra-vars "host=www user=mageedu"

    通过roles传递

③主机变量:定义在inventory中的主机之后的变量;

        host:var

[root@localhost ~]# vim /etc/ansible/hosts
...
[websrvs]
172.16.61.2 host=mail

④组变量:定义在inventory中的组上的变量

  [group_name:vars]

    var1=value

    var2=value

   [websrvs]

   [websrvs:vars]


变量使用示例:

[root@localhost ~]# vim second.yml

- hosts: websrvs
  remote_user: root
  vars:                                 #定义变量
     username: student       
     password: tianzhuang
  tasks:
   - name: add user
     user: name={{ username }} state=present     #{{  }}引用变量
   - name: set password
     shell: /bin/echo {{ password }} | /usr/bin/passwd --stdin {{ username }}
     
[root@localhost ~]# ansible-playbook second.yml

PLAY [websrvs] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [172.16.61.2]
ok: [172.16.61.3]

TASK: [add user] ************************************************************** 
changed: [172.16.61.3]
changed: [172.16.61.2]

TASK: [set password] ********************************************************** 
changed: [172.16.61.3]
changed: [172.16.61.2]

PLAY RECAP ******************************************************************** 
172.16.61.2                : ok=3    changed=2    unreachable=0    failed=0   
172.16.61.3                : ok=3    changed=2    unreachable=0    failed=0

[root@localhost ~]# ansible-playbook second.yml --extra-vars "username=tz"  #也可以在命令行中利用扩展进行变量赋值,此种方法优先级高于在yaml文件中定义的变量

PLAY [websrvs] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [172.16.61.3]
ok: [172.16.61.2]

TASK: [add user] ************************************************************** 
changed: [172.16.61.2]
changed: [172.16.61.3]

TASK: [set password] ********************************************************** 
changed: [172.16.61.2]
changed: [172.16.61.3]

PLAY RECAP ******************************************************************** 
172.16.61.2                : ok=3    changed=2    unreachable=0    failed=0   
172.16.61.3                : ok=3    changed=2    unreachable=0    failed=0


(2)inventory参数:

    ansible基于ssh连接inventory中指定的远程主机时,将以此处的参数指定的属性进行;

    ansible_ssh_port    

    ansible_ssh_user

    ansible_ssh_pass

    ansible_sudo_pass

[root@localhost ~]# vim /etc/ansible/hosts
...
[websrvs]
172.16.61.2 ansible_ssh_user=root ansible_ssh_pass=mageedu


(3)条件测试:

    在某task后面添加when语句即可实现条件测试功能;when语句支持jinjia2语法;

[root@localhost ~]# vim third.yml

- hosts: websrvs
  remote_user: root
  tasks:
  - name: install web server
    apt: name=apache2
    when: ansible_os_family == "Debin"     #添加when语句判断操作系统为Debin系时使用apt命令安装apache2
  - name: say hello
    command: /bin/echo "hello"

[root@localhost ~]# ansible-playbook third.yml

PLAY [websrvs] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [172.16.61.3]
ok: [172.16.61.2]

TASK: [install web server] **************************************************** 
skipping: [172.16.61.3]     #目标远程节点为CentOS系所以直接跳过
skipping: [172.16.61.2]

TASK: [say hello] ************************************************************* 
changed: [172.16.61.3]
changed: [172.16.61.2]

PLAY RECAP ******************************************************************** 
172.16.61.2                : ok=2    changed=1    unreachable=0    failed=0   
172.16.61.3                : ok=2    changed=1    unreachable=0    failed=0

(4)迭代:

    在task中调用内置的item变量;在某task后面使用with_items语句来定义元素列表

     

- hosts: websrvs
  remote_user: root
  tasks:
  - name: add two users
    user: name={{ item }} state=present
    with_items:
        - testuser1
        - testuser2


注:迭代中列表中的每个元素可以为字典格式;


(5)handlers:

    也是task,但只有其关注的条件满足时,才会被触发执行

 ...
 Listen 8080       #在director主机上更改httpd配置文件监听8080端口
 
[root@localhost ~]# vim fifth.yml

- hosts: websrvs
  remote_user: root
  tasks:
    - name: install config file
      copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
      notify: restart httpd             #文件改变时通知给触发器
    - name: start service
      service: name=httpd state=started
  handlers:                             #定义触发器
    - name: restart httpd
      service: name=httpd state=restarted
      
[root@localhost ~]# ansible-playbook fifth.yml

PLAY [websrvs] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [172.16.61.2]
ok: [172.16.61.3]

TASK: [install config file] *************************************************** 
changed: [172.16.61.3]
changed: [172.16.61.2]

TASK: [start service] ********************************************************* 
ok: [172.16.61.3]
ok: [172.16.61.2]

NOTIFIED: [restart httpd] ***************************************************** 
changed: [172.16.61.3]
changed: [172.16.61.2]

PLAY RECAP ******************************************************************** 
172.16.61.2                : ok=4    changed=2    unreachable=0    failed=0   
172.16.61.3                : ok=4    changed=2    unreachable=0    failed=0     
 
 
LISTEN     0      128                             :::8080                           :::* #远程节点已经监听到8080端口了.


(6)templates:

    用于生成文本文件(配置文件);模块文件中可使用jinjia2表达式,表达式要定义在{{ }},也可以简单的执行变量替换

[websrvs]          #在inventory中配置主机变量
172.16.61.2 httpd_port=8080
172.16.61.3 httpd_port=8088


Listen {{ httpd_port }}    #在director中更改httpd配置文件监听端口为变量名

[root@localhost ~]# cp ./httpd.conf ./httpd.conf.jinjia2  #更改为jinjia2文件格式

- hosts: websrvs
  remote_user: root
  tasks:
    - name: install config file
      template: src=/root/httpd.conf.jinjia2 dest=/etc/httpd/conf/httpd.conf  #此处使用template模块
      notify: restart httpd
    - name: start service
      service: name=httpd state=started
  handlers:
    - name: restart httpd
      service: name=httpd state=restarted

[root@localhost ~]# ansible-playbook fifth.yml 

PLAY [websrvs] **************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [172.16.61.3]
ok: [172.16.61.2]

TASK: [install config file] *************************************************** 
changed: [172.16.61.3]
ok: [172.16.61.2]

TASK: [start service] ********************************************************* 
ok: [172.16.61.2]
ok: [172.16.61.3]

NOTIFIED: [restart httpd] ***************************************************** 
changed: [172.16.61.3]

PLAY RECAP ******************************************************************** 
172.16.61.2                : ok=3    changed=0    unreachable=0    failed=0   
172.16.61.3                : ok=4    changed=2    unreachable=0    failed=0            
      
LISTEN     0      128                             :::8088                           :::*      
LISTEN     0      128                             :::8080                           :::*

(7)roles:

    1)roles用于实现“代码复用”;

    2)roles以特定的层次型个好似组织起来的playbook元素(variables,tasks,templates,handlers);可被playbook以role的名字直接进行调用;












你可能感兴趣的:(ansible)