运维自动化之ansible

ansible的基本架构

​ host inventory主机清单

​ playbook相当于脚本,

​ modules模块

ansible工作原理

​ 通过执行命令,或ansible playbook,cmdb

ansible配置文件

​ /etc/ansible/ansible.cfg主配置文件,配置ansible工作特性

​ /etc/ansible/hosts/主机清单

​ /etc/ansible/roles/存放角色的目录

程序

​ /usr/bin/ansible 主程序,临时命令执行工具

​ /usr/bin/ansible-doc 查看配置文档,模块功能查看工具

​ /usr/bin/ansible-galaxy 下载/上传优秀代码或roles模块的官网平台

​ /usr/bin/ansible-playbook 定制自动化任务,编排剧本工具/usr/bin/ansible-pull 远程执行命令的工具

​ /usr/bin/ansible-console 基于console界面与用户交互的执行工具

主机清单inventory

​ /etc/ansible/hosts文件格式

​ [webservers]

​ www1.magedu.com:2222

​ www2.magedu.com

​ [dbservers]

​ db1.magedu.com

​ db2.magedu.com

​ 可以分组

​ [websrvs]

​ 192.168.30.101

​ 192.169.30.102

​ [dbsrvs]

​ 192.168.30.10[1:3]

​ **ansible系列命令**

​ ansible ansible-doc ansible-playbook ansible-vault

​ ansible-console ansible-galaxy ansible-pull

​ ansible-doc:显示模块帮助

​ ansible-doc options

​ -l,- -list列出可用模块

​ -s, – -snippet显示指定模块的playbook片段

​ ansible <host-pattern> -m module_name

​ – -version 显示版本

​ -m module 指定模块,默认为command

​ -v 详细过程 -vv -vvv更详细

​ – -list-hosts 显示主机列表,可简写- -list

​ -k, – -ask-pass 提示连接密码,默认key验证(适合于所有的主机口令都一致)

​ -K, – -ask-become-pass 提示输入sudo

​ -C,- -check 检查,并不执行

​ -T, – -timeout=TIMEOUT 执行命令的超时时间,默认10s

​ -u, – -usr=REMOTE_USER 执行远程的用户

​ -b, – -become 代替旧版的sudo切换

​ usermod -aG wheel wang

​ sudo nopasswd

​ echo export EDITOR >> /etc/profile.

​ 1、Ansible 172.20.104.99 172.20.104.66 -m ping -k

​ ansible的Host-pattern

​ 匹配主机的列表

​ All:表示所有inventory中的所有主机

​ ansible all -m ping

​ *:通配符

​ ansible “*” -m ping

​ 或关系

​ ansible “websrvs:appsrvs” -m ping

​ ansible “192.168.1.10:192.168.1.20” -m ping

​ 逻辑与

​ ansible “websrvs:&dbsrvs”

​ 在websrvs组,但不在dbsrvs组中的主机

​ 逻辑非

​ ansible ‘websrvs:!dbsrvs’ -m ping

​ 在websrvs组,但不在dbsrvs组中的主机

​ 注意:此处为单引号

​ 综合逻辑

​ ansible ‘websrvs:dbsrvs:&appsrvs:!ftpsrvs’ -m ping

​ 正则表达式

​ ansible “websrvs:&dbsrvs” -m ping

​ ansible “~(web|db).*.magedu.com” -m ping

ansible常用模块

COMMAND:在远程主机执行命令,默认模块,可忽略-m选项

​ ansible srvs -m command -a ‘service vsftpd start’

​ ansible srvs -m command -a ‘echo magedu |passwd – -stdin wang’ 不成功

​ 此命令不支持$VARNAME< > |;&等,用shell模块实现

Shell:和command相似,用shell执行命令

​ ansible srv -m shell -a ‘echo magedu|passwd – -stdin wang’

​ 调用bash执行命令,类似cat /tmp/stanley.md |awk -F ‘|” {print 2}’ &> /tmp/example.txt这些复杂命令,即使需要的结果拉回执行命令的机器

Script :运行脚本

​ -a “/PATH/TO/SCRIPT_FILE”

​ ansible websrvs -m script -a f1.sh

Copy :从服务器复制文件到客户端

​ ansible srv -m copy -a “src=/root/f1.sh dest=/tmp/f2.sh owner=wang mode=600 backup=yes”

​ 如目标存在,默认覆盖,此处指定备份

​ ansible srv -m copy -a “content=’test content\n’ dest=/tmp/f1.txt” 利用内容,直接生成目标文件

cron 计划任务

​ 支持时间:minute, hour,day,month,weekday

​ ansible srv -m cron -a “minute=*/5 job=’/usr/sbin/ntpdate 172.16.0.1 &>/dev/null’name=synctime” 创建任务

​ ansible srv -m cron -a ‘state=absent name=synctime’ 删除任务

ansible all -m cron -a 'minute=* weekday=1,3,5' job="/usr/bin/wall  FBI warning" name=warningcron'设置计划任务
ansible all -m cron -a 'disabled=false job="/usr/bin/wall  FBI warning" name=warningcron'取消计划任务

Fetch :从客户端取文件至服务器端,copy相反,目录可先tar

​ ansible srv -m fetch -a ‘src=/root/a.sh dest=/data/sciripts’

​ ansible all -m shell -a ‘tar Jcf log.tar.xz /var/log/*.log’

File :设置文件属性

​ ansible srv -m file -a “path=/root/a.sh owner=wang mode=755”

​ ansible web -m file -a ‘src=/app/testfile dest=/app/testfile-link state=link’

Hostname:管理主机名

​ ansible node1 -m hostname -a “name=websrv”

yum:管理包

​ ansible srv -m yum -a ‘name=httpd state=latest’ 安装

​ ansible srv -m yum -a ‘name=httpd state=absent’ 删除

Service:管理服务

​ ansible-doc -s service

​ ansible websrvs – -list

​ ansible srv -m service -a ‘name=httpd state=stopped’

​ ansible srv -m service -a ‘name=httpd state=started enabled=yes|no’

​ ansible srv -m service -a ‘name=httpd state=reloaded’

​ ansible srv -m sercice -a ‘name=httpd state=restarted’

User:管理用户

​ ansible-doc -u user

​ ansible srv -m user -a ‘name=user1 comment=”test user” uid=2048 home=/app/user1 group=root’

​ ansible srv -m user -a ‘name=sysuser1 system=yes home=/app/user1 group=root’

​ ansible srv -m user -a ‘name=user1 state=absent remove=yes’#删除用户及家目录等数据

ansible websrvs -m user -a ‘name=nginx shell=/sbin/nologin/ system=yes home=/var/nginx groups=root,bin,uid=80 comment=”nginx service”‘ #创建账号

​ ansible websrvs -a ‘getent passwd nginx’#在另一台电脑上查看

Group:管理组

​ ansible srv -m group -a “name=nginx system=yes gid=80”

​ ansible srv -m group -a “name=nginx state=absent”

ansible系列命令

​ ansible-galaxy

​ 连接https://galaxy.ansible.com下载相应的roles

​ 列出所有已安装的galaxy

​ ansible-galaxy list

​ 安装galaxy

​ ansible-galaxy install geerlingguy.redis

​ 删除galaxy

​ ansible-galaxy remove geerlinguy.redis

​ ansible-pull

​ 推送命令至远程,效率无限提升,对运维要求较高

​ ansible-playbook

​ ansible-playbook hello.yml

#mkdir ansible
#vim hello.yaml
---
-hosts: websrvs #
 remote_user: root  #以root的身份在远程主机运行
 
 tasks:
 - name: hello
   command: hostname
#ansible-playbook hello.yml

​ ansible-vault

​ 管理加密解密yml文件

​ ansible-vault [create|decrypt|edit|encrypt|rekey|view]

​ ansible-vault encrypt hello.yml 加密

​ ansible-vault decrypt hello.yml 解密

​ ansible-vault view hello.yml 查看

​ ansible-vault edit hello.yml 编辑加密文件

​ ansible-vault rekey hello.yml 修改口令

​ ansible-vault create new.yml 创建新文件

​ ansible-console:2.0+新增,可交互执行命令,支持tab

​ root@test(2)[f:10]$

​ 执行用户@当前操作的主机组(当前组的主机数量)[f:并发数]$

​ 设置并发数:forks n 例如:forks 10

​ 切换组:cd主机组 例如:cd web

​ 列出当前组主机列表:list

​ 列出所有的内置命令:?或help

​ 示例:

​ root@all(2)[f:5]$list

​ root@all(2)[f:5]$ cd appsrvs

​ root@appsrvs(2)[f:5]$list

​ root@appsrvs(2)[f:5]$yum name=httpd state=present

​ root@appsrvs(2)[f:5]$service name=httpd state=started

​ ansible-console

​ command hostname#在远程主机执行hostname

playbook

playbook是由一个或多个“play”组成的列表

play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible的task定义好的角色。从根本上来讲,所谓的task无非是调用ansible的一个module。将多个play组织在一个playbook中,即可以让他们联同起来按事先编排的机制同唱一台大戏。

playbook采用YAML语言编写

yaml介绍

yaml语法简介

缩进必须是统一的,不能空格和tab混用

一个name只能包括一个task

list:列表,其所有元素均使用“-”打头

示例:
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango

dictionay:字典,通常由多个key与value构成

示例:
# An employee record
name:Example Developer
job:Developer
skill:Elite
也可以将key:value放置于{}中进行表示,用,分隔多个key.value
示例:
---
# An employee record
{name:Example Developer,job:Developer,skill:Elite}

YAML语法

示例
name:john smith
age:41
gender:male
spouse:
  name:Jane Smith
  age:37
  gender:Female
childrem:
  - name:Jimmy Smith
    age 17
    gender:Male
  - name:Jenny Smith
    age 13
    gender:Female

playbook核心元素

hosts:执行的远程主机列表

tasks:任务集

Variables:内置变量或自定义变量在playbook中调用

Templates 模版,可替换模版文件中的变量并实现一些简单逻辑的文件

handlers和notity结合使用,由特定条件触发的操作,满足条件方才执行,否则不执行

tags标签 指定某条任务执行,用于选择运行playbook中的部分代码。ansibe具有幂等性,因此会自动跳过没有变化的部分,即便如此,有些代码为测试其确实没有发生变化的时间依然会非常地长。此时,如果确信其没有变化,就可以通过tags跳过此些代码片断。

ansible-playbook -t tagsname useradd.yml

playbook基础组件

​ hosts:

# vim file.yml
---
- hosts: websrvs
  remote_user: root
  
  tasks: 
    - name: create new file
      file: name=/data/newfile state=touch
    - name: create new user
      user: name=test2 system=yes shell=/sbin/nologin
    - name: install package
      yum: name=httpd 
    - name: copy html
      copy: src=/var/www/html/index.html dest=/var/www/html/
    - name: start service
      service: name-httpd state=started enable=yes
#curl 192.168.30.101
welcome to magedu

Remote_user

task列表和action

tasks:任务列表

palybook如果中间有一个命令或脚本是错误的,不会执行后续的命令,可使用下面的方法解决:

​ tasks:

​ -name:run this command and ignore the result

​ shell:/usr/bin/somecommand || /bin/true

​ 或者使用ignore_errors来忽略错误信息:

​ tasks:

​ -name:run this command and ignore the result

​ shell:/usr/bin/somecommand

​ ignore_errors:true

运行playbook

运行playbook的方式

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

常见选项:

​ –check 只检测可能会发生的改变,但不真正执行操作

​ —list-hosts列出运行任务的主机

​ –limit主机列表 只针对主机列表中的主机执行

​ -v显示过程 -vv -vvv更详细

playbook中handlers使用

- hosts: websrvs
  remote_user: root
     
  tasks:
    -name: install httpd
        yum: name=httpd state=present
    -name: install configure file
      copy: src=files/httpd.conf dest=/etc/httpd/conf/
      notify: restart httpd #对应下面handlers
    -name: ensure apache is running
      service: name=httpd state=started enabled=yes
    
  handlers:
    -name: restart httpd
      service: name=httpd status=restarted

playbook中tags使用

有标签的效果是可以单独执行一个标签

示例:
- hosts: websrvs
  remote_user: root
     
  tasks:
    -name: install httpd
        yum: name=httpd state=present
        
    -name: install configure file
      copy: src=files/httpd.conf dest=/etc/httpd/conf/
      tags:conf
      
    -name: ensure apache is running
     tags:service
     service: name=httpd state=started enabled=yes
    
  ansible-playbook -t conf httpd.yml

ansible websrvs -m service -a ‘name=httpd state=stoped’#停止服务

Ansible-playbook -t rshttpd httpd.yml

playbook中变量使用

变量的来源:

​ 1、ansible setup facts远程主机的所有变量都可直接调用

​ 2、/etc/ansible/hosta中定义

示例:
vim app.yml
---
- hosts: appsrvs
  remote_user: root
     
  tasks:
    -name: set hostname
      hostname: name=www{{http_port}}.magedu.com

​ 定义通用的分组的变量

​ [websrvs]

​ 192.168.30.101 http_port=81

​ 192.168.30.101 http_port=81

​ [websrvs:vars]

​ nodename=www

​ domainname=.magedu.com

​ 3、通过命令行指定变量,优先级别最高

​ ansible-playbook -e varname=value

变量的优先级,命令行的大于playbook大于主机清单的

示例:
vim app.yml
---
- hosts: appsrvs
  remote_user: root
     
  tasks:
    -name: install package
      yum: name={{ pkname1 }}
    -name: start service
    
#ansible-playboook -e 'pkname=vsftpd' app.yml

​ 4、在playbook中定义

​ vars:

​ -var1:value1

​ -var2:value2

示例:
vim app.yml
---
- hosts: appsrvs
  remote_user: root
  vars:
    - pkname1: httpd
    - pkname2: tftpd
  tasks:
    -name: install package
      yum: name={{ pkname1 }}
    -name: install package
      yum: name={{ pkname2 }}
vim var.yml
---
- hosts: websrvs
  remote_user: root
  
tasks: 

模版templates

示例:
mkdir /etc/ansible/templates
#cp         nginx.conf/j2
#vim testtesttempl.yml
nginx.conf/j2
---
- hosts: websrvs
remote_user: root

tasks:
  - name: install package
    yum: name=nginx
  - name: copy template
    template: src=nginx.cong.j2 dest=/etc/nginx/nginx.conf
  - name: start service
    service: name=nginx state=state=srarted enable=yes
 #ansible-playbook -C testtempl.yml
 在其它的机器上测试
 #ansible websrvs -m shell -a 'ss -ntpl'    #查看端口
 #ansible websrvs -m shell -a 'ps aux|grep nginx'

示例:


#vim testtesttempl.yml
nginx.conf/j2
---
- hosts: websrvs
remote_user: root

tasks:
  - name: install package
    yum: name=nginx
  - name: copy template
    template: src=nginx.cong.j2 dest=/etc/nginx/nginx.conf
    notify: restart service
  - name: start service
    service: name=nginx state=state=srarted enable=yes
    
  handlers:
     - name: restart service
     service: name=nginx.cong.j2

when

#vim testtesttempl.yml
---
- hosts: websrvs
remote_user: root
vars:
  - http_port: 88
  
tasks:
  - name: install package
    yum: name=nginx
  - name: copy template for centos7
    template: src=nginx.congf7.j2 dest=/etc/nginx/nginx.conf
    when: ansible_distribution_major_version == "7"
    notify: restart service
  - name: copy template for centos6
    template: src=nginx.congf6.j2 dest=/etc/nginx/nginx.conf
    when: ansible_distribution_major_version == "6"
    notify: restart service
  - name: start service
    service: name=nginx state=srarted enable=yes
    
handlers:
  - name: restart service
    service: name=nginx state=restarted

迭代:with_items

vim testtitem.yml
---
- host: all
remote_user: root

tasks: 
  - name: create some files
    file: name=/data/{{ item }} state=touch
    when: ansible_distribution_major_version == "7"
    with_items:
      - file1
      - file2
      - file3
  - name=: install some packages
    yum: name={{ item }}
    with_items:
      - htop
      - sl
      - hping3
      在另外两台机器上验证
#ansible all -m shell -a 'ls /data/ -l'
#ansible all -m shell -a 'rpm -q htop sl hping3'

创建组

vim testitem2.yml
---
- host: all
remote_user: root

tasks: 
  - name: create some files
    group: name={{ item }} 
    when: ansible_distribution_major_version == "7"
    with_items:
      - g1
      - g2
      - g3
  #ansible-playbook testitem2.yml

创建3个组,并且创建3个用户,并分别把三个用户分别加到三个组里面

迭代嵌套子变量

vim tesitem3.yml
---
- host: websrvs
remote_user: root

tasks: 
  - name: create some groups
    group: name={{ item }} 
    when: ansible_distribution_major_version == "7"
    with_items:
      - g1
      - g2
      - g3
   - name: create some users
     user: name={{itwm.name}}group={{item.group}}
     with_items:
       -{ name: 'user1',group: 'g1' }
       -{ name: 'user2',group: 'g2' }
       -{ name: 'user3',group: 'g3' }
  #ansible-playbook tesitem3.yml
  #ansible all -m shell 'genten passwd'

for循环

利用for循环,生成一个语句块,生成一些配置信息,监听端口81,82,83

vim testfor.yml
---
- hosts: websrvs
remote_user: root
vars:
  ports: 
    - 81
    - 82
    - 83
tasks:
  - name: copy conf
    template: src=for1.conf.j2 dest=/data/for1.conf
#vim for1.conf.j2
{% for port in ports %}
server{
        listen {{port}}
}
{% endfor %}

用字典的方式来改

vim testfor2.yml
---
- hosts: websrvs
remote_user: root
vars:
  ports: 
    - listen_port:81
    - listen_port:82
    - listen_port:83
tasks:
  - name: copy conf
    template: src=for1.conf.j2 dest=/data/for1.conf
#vim /templatefor1.conf.j2
{% for port in ports %}
server{
        listen {{ port.listen_port }}
}
{% endfor %}
#ansible-playbook  testfor2.yml

嵌套

vim testfor2.yml
---
- hosts: websrvs
remote_user: root
vars:
  ports: 
    - web1:
    port: 81
    name: web1.magedu.com
    rootdir: /data/website1
    - web2:
    port: 82
    name: web2.magedu.com
    rootdir: /data/website2
    - web3:
    port: 83
    name: web3.magedu.com
    rootdir: /data/website3
tasks:
  - name: copy conf
    template: src=for1.conf.j2 dest=/data/for1.conf
#vim /templatefor3.conf.j2
{% for p in ports %}
server{
        listen {{ p.listen_port }}
        servername{{ p.name }}
        ducumentroot{{ p.rootdir }}
}
{% endfor %}
#ansible-playbook  testfor3.yml
注意调用的路径问题,
在其它机器上查看
cat /data/for3.conf

if的用法

vim testfor2.yml
---
- hosts: websrvs
remote_user: root
vars:
  ports: 
    - web1:
    port: 81
    #name: web1.magedu.com
    rootdir: /data/website1
    - web2:
    port: 82
    name: web2.magedu.com
    rootdir: /data/website2
    - web3:
    port: 83
    #name: web3.magedu.com
    rootdir: /data/website3
tasks:
  - name: copy conf
    template: src=for4.conf.j2 dest=/data/for4.conf
#vim /templatefor4.conf.j2
{% for p in ports %}
server{
        listen {{ p.listen_port }}
{% if p.name is defined %}      
        servername{{ p.name }}
{% endif %}     
        ducumentroot{{ p.rootdir }}
}
{% endfor %}
#ansible-playbook  testfor4.yml

roles

roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲,roles就是通过分别将变量、文件、任务、模版及处理器放置于单独的目录中,并可以便捷地include他们的一种机制。

部署nginx服务,
1、创建nginx用户、
2、创建nginx组、
3、yum安装包、
4、配置template:nginx
5、启动服务。
#cd /etc/ansible/
#mkdir roles/{httpd,mysql memcache}
#mkdir roles/nginx
#规划子目录 一个放任务,一个放模版
#cd /nginx
#mkfir tasks templates
#cd tasks
#vim group.yml
- name: create group
  group: name=nginx gid=80
#vim user.yml
- name: create user
  user: name=nginx uid=80 group=nginx system=yes shell=/sbin/nologin
#vim yum.yml
- name: install package
  yum: name:nginx
#vim start.yml
- name: start service
  service: name=nginx state=start enable=yes
#vim restart.yml
- name: restart service
  service: name=nginx state=start enable=yes  
#cp /etc/nginx/conf.d
worker_processes {{ ansible_processor_vcpus+2 }};
vim templ.yml
- name: copy conf
  template: src=nginx.cong.j2 dest=/etc/nginx/nginx.conf
# vim main.yml
- include: group.yml
- include: user.yml
- include: yum.yml
- include: templ.yml
- include: start.yml
# 切换到和roles平级的目录
#vim nginx_role.yml
- hosts: websrvs
  remote_user: root
  roles:
      role: nginx
 #ansible-playbook -C nginx_role.yml

定义httpd别的角色

cd roles/httpd/
mkdir tasks
cd tasks
ls
#创建apache用户
#vim user.yml
- name: create user
  user: name=apache system=yes shell=/sbin/nologin
#vim copyfile.yml
- name: copy files
  copy: src=/etc/httpd.conf dest=/data/ owner=apache
#vim main.yml
- include: user.yml
- include: copyfile.yml
#vim httpd_role.yml
- hosts: websrvs
  remote_user: root
  
  roles: 
  - httpd
#ansible-playbook httpd_role.yml

在一个角色中跨项目调用另一个角色或着两个角色都使用。假如一个提供web服务,一个提供php服务。

Ansible all -m shell -a ‘userdel nginx’

#vim some_role.yml
- hosts: websrvs
  remote_user: root
  
  roles: 
  - role: httpd
  - role: nginx
  引用另外的角色,比如在nginx中调用httpd的copy.yml
  #vim roles/nginx/tasks/main.yml
- include: group.yml
- include: user.yml
- include: yum.yml
- include: templ.yml
- include: start.yml
- include: roles/httpd/tasks/copyfile.yml
#ansible-playbook nginx_role.yml

roles playbook tags使用

在角色中加标签tags

- hosts: websrvs
  remote_user: root
  roles:
    - {{ role: httpd,tags:['web','httpd']}}
    - {{ role: nginx,tags:['web','nginx']}}
    - {{ role: app,tags:"app"}}
#cp -r nginx/ app/
#ansible-playbook -t web some_role.yml  #只运行web标签
- hosts: all
  remote_user: root
  roles:
    - { role: httpd,tags:['web','httpd']}
    - { role: nginx,tags:['web','nginx'],when: ansible_distrubution_major_version == "7"}}
    - { role: app,tags:"app"}

#ansible-playbook some_role.yml #只运行web标签

综合实验:

以httpd为例,创建app用户
mkdir root/anxible/roles/app
mkdir tasks templates vars handers files
cd tasks
#vim group.yml
- name: create group
  group: name=app system=yes gid=123
  
#vim user.yml
- name: create user
  user: name=app group=app system=yes shell=/sbin/nologin uid=123
#vim yum.yml
- name: install package
  yum: name=httpd
#cp /etc/http/conf/httpd.conf ../templates/httpd.j2
vim ../templates/httpd.j2
listen {{ ansible_processor_vcpus*10 }}
user {{ username }}
group {{ group }}
#vim        定义变量
 username: app
 groupname: app
#vim tasks/templates.yml
- name: copy conf
  template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  notify:  restart service
#vim handlers/restart.yml
- name: restart service
  service: name=httpd state=restarted
#vim task
- name: start service
service: name=httpd state=started enable=yes
#tree
#touch files/vhosts.conf
#vim 
- name: copy config
  copy: src=vhosts.conf dest=/etc/httpd/conf.d/ owner=app 
  
#vim roles/main.yml
- include: group.yml
- include: user.yml
- include: yum.yml
- include: templ.yml
- include: copu.yml
- include: start.yml
#ansible-playbook -C app.yml

tips

rpm -ql memcached

cat /etc/sysconfigmemcached

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/100169

发表评论

登录后才能评论

联系我们

400-080-6560

在线咨询:点击这里给我发消息

邮件:1823388528@qq.com

工作时间:周一至周五,9:30-18:30,节假日同时也值班