absible自动化运维入门学习

介绍

特性
模块化:调用特定的模块完成特定任务,支持自定义模块,可使用任何编程语言写模块。
Paramiko(python对ssh的实现),PyYAML,Jinja2(模板语言)三个关键模块。
基于Python语言实现。
部署简单,基于python和SSH(默认已安装),agentless,无需代理不依赖PKI(无需ssl)。
安全,基于OpenSSH开源实现。
幂等性:一个任务执行1遍和执行n遍效果一样,不因重复执行带来意外情况。
支持playbook编排任务,YAML格式,编排任务,支持丰富的数据结构。
较强大的多层解决方案role。
Ansible 架构
在这里插入图片描述组合INVENTORY、API、MODULES、PLUGINS的绿框,可以理解为是ansible命令工具,其为核心执行工具。
INVENTORY:Ansible管理主机的清单/etc/anaible/hosts。
MODULES:Ansible执行命令的功能模块,多数为内置核心模块,也可自定义。
PLUGINS:模块功能的补充,如连接类型插件、循环插件、变量插件、过滤插件等,该功能不常用。
API:供第三方程序调用的应用程序编程接口。
CMDB(配置管理数据库) API 调用。
PUBLIC/PRIVATE CLOUD API调用。
PLAYBOOKS:任务剧本(任务集),编排定义Ansible任务集的配置文件,由Ansible顺序依次执行,通常是JSON格式的YML文件。
注意事项
执行ansible的主机一般称为主控端,中控,master或堡垒机。
主控端Python版本需要2.6或以上。
windows 不能做为主控端。
被控端Python版本小于2.4,需要安装python-simplejson。
被控端如开启SELinux需要安装libselinux-python。
在这里插入图片描述

部署

1.Epel源安装
[root@k8s-master1 ~]# yum -y install ansible
2.编译安装
yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto
tar xf ansible-1.5.4.tar.gz
cd ansible-1.5.4
python setup.py build
python setup.py install
mkdir /etc/ansible
cp -r examples/* /etc/ansible
3.git方式安装
git clone git://github.com/ansible/ansible.git --recursive
cd ./ansible
source ./hacking/env-setup
4.pip方式安装
yum install python-pip python-devel
yum install gcc glibc-devel zibl-devel rpm-bulid openssl-devel
pip install --upgrade pip
pip install ansible –upgrade

ansible常用工具

/usr/bin/ansible 主程序,临时命令执行工具
/usr/bin/ansible-doc 查看配置文档,模块功能查看工具
/usr/bin/ansible-galaxy 下载/上传优秀代码或Roles模块的官网平台
/usr/bin/ansible-playbook 定制自动化任务,编排剧本工具
/usr/bin/ansible-pull 远程执行命令的工具
/usr/bin/ansible-vault 文件加密工具
/usr/bin/ansible-console 基于Console界面与用户交互的执行工具
Ansible工具
ansible主要用于临时命令使用场景, Ansible-playbook 主要用于长期规划好的,大型项目的场景,需要有前期的规划过程。
通过ssh协议,实现对远程主机的配置管理、应用部署、任务执行等功能。使用此工具前,先配置ansible主控端能基于密钥认证的方式联系各个被管理节点。
ansible [-m module_name] [-a args]
-m module #指定模块,默认为command
-v #详细过程 –vv -vvv更详细
–list-hosts #显示主机列表,可简写 –list
-u, --user=REMOTE_USER #执行远程执行的用户
-k, --ask-pass #提示输入ssh连接密码,默认Key验证
-C, --check #检查,并不执行
-T, --timeout=TIMEOUT #执行命令的超时时间,默认10s
–become-user=USERNAME #指定sudo的runas用户,默认为root
-K, --ask-become-pass #提示输入sudo时的口令
-b, --become #代替旧版的sudo 切换
All :表示Inventory中的所有主机
ansible all –m ping
:通配符
ansible 192.168.1.
-m ping
或关系
ansible “192.168.1.10:192.168.1.20” -m ping
逻辑与
ansible “websrvs:&dbsrvs” –m ping
逻辑非
ansible ‘websrvs:!dbsrvs’ –m ping #注意:此处为单引号
综合逻辑
ansible ‘websrvs:dbsrvs:&appsrvs:!ftpsrvs’ –m ping
正则表达式
ansible “~(web|db).*.cn.com” –m ping
ansible命令执行过程
1.加载自己的配置文件 默认/etc/ansible/ansible.cfg
2.加载自己对应的模块文件,如:command
3.通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户$HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件
4.给文件+x执行
5.执行并返回结果
6.删除临时py文件,退出
ansible 的执行状态
绿色:执行成功并且不需要做改变的操作
黄色:执行成功并且对目标主机做变更
红色:执行失败
ansible使用范例
ansible all -m ping -u wang -k #以wang用户执行ping存活检测
ansible all -m ping -u wang -k -b #以wang sudo至root执行ping存活检测
ansible all -m ping -u wang -k -b --become-user=jerome #以wang sudo至jerome用户执行ping存活检测
ansible all -m command -u wang -a ‘ls /root’ -b --become-user=root -k -K #以wang sudo至root用户执行ls
ansible-doc工具
此工具用来显示模块帮助。
ansible-doc [options] [module…]
ansible-doc -l #列出所有模块
ansible-doc ping #查看指定模块帮助用法
ansible-doc -s ping #查看指定模块帮助用法
ansible-playbook工具
此工具用于执行编写好的 playbook 任务
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工具
此工具可交互执行命令,支持tab,ansible 2.0+新增
提示符格式
执行用户@当前操作的主机组 (当前组的主机数量)[f:并发数]$
设置并发数: forks n 例如: forks 10
切换组: cd 主机组 例如: cd web
列出当前组主机列表: list
列出所有的内置命令: ?或help
ansible-galaxy工具
ansible-galaxy list #列出所有已安装的galaxy
ansible-galaxy install geerlingguy.mysql #安装galaxy
ansible-galaxy remove geerlingguy.redis #删除galaxy

常用模块

1.Command 模块
在远程主机执行命令,此为默认模块,可忽略-m选项。
注意:此命令不支持 $VARNAME < > | ; & 等,用shell模块实现。
ansible websrvs -m command -a ‘chdir=/etc cat centos-release’
ansible websrvs -m command -a ‘chdir=/etc creates=/data/f1.txt cat centos-release’
ansible websrvs -m command -a ‘chdir=/etc removes=/data/f1.txt cat centos-release’
有些命令command模块不支持
ansible websrvs -m command -a ‘service vsftpd start’
ansible websrvs -m command -a ‘echo magedu |passwd --stdin wang’
ansible websrvs -m command -a ‘echo hello > /data/hello.log’
ansible websrvs -m command -a “echo $HOSTNAME”
2.Shell模块
和command相似,用shell执行命令
ansible websrvs -m shell -a ‘echo hello > /data/hello.log’
ansible websrvs -m shell -a ‘cat /data/hello.log’
注意:调用bash执行命令 类似 cat /tmp/test.md | awk -F‘|’ ‘{print 1,1,1,2}’ &> /tmp/example.txt 这些复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器。
3.Script模块
在远程主机上运行ansible服务器上的脚本
ansible all -m script -a ‘/etc/ansible/script/test1.sh’
4.Copy模块
从ansible服务器主控端复制文件到远程主机
ansible websrvs -m copy -a “src=/root/test1.sh dest=/tmp/test2.sh owner=wang mode=600 backup=yes” #如目标存在,默认覆盖,此处指定先备份
ansible websrvs -m copy -a “content=‘test line1\ntest line2’ dest=/tmp/test.txt” #指定内容,直接生成目标文件
ansible websrvs -m copy -a “src=/etc/ dest=/backup” #复制/etc/下的文件,不包括/etc/目录自身
5.Fetch模块
从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录
ansible webservers2 -m fetch -a “src=/etc/centos-release dest=/root”
6.File模块
设置文件属性
ansible all -m file -a ‘path=/data/test.txt state=touch’ #创建空文件
ansible all -m file -a ‘path=/data/test.txt state=absent’ #删除文件
ansible all -m file -a "path=/root/test.sh owner=wang mode=755“ #设置权限
ansible all -m file -a “path=/data/mysql state=directory owner=mysql group=mysql” #创建目录
ansible all -m file -a ‘src=/data/testfile dest=/data/testfile-link state=link’ 创建软链接
7.unarchive模块
解包解压缩
将ansible主机上的压缩包解压到远程主机的特定目录,设置copy=yes
将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no
ansible all -m unarchive -a ‘src=/data/foo.tgz dest=/var/lib/foo’
ansible all -m unarchive -a ‘src=/tmp/foo.zip dest=/data copy=no mode=0777’
8.Archive模块
打包压缩
ansible websrvs -m archive -a ‘path=/var/log/ dest=/data/log.tar.bz2 format=bz2 owner=wang mode=0600’
9.Hostname模块
管理主机名
ansible node1 -m hostname -a “name=websrv”
10.Cron模块
计划任务
支持时间:minute,hour,day,month,weekday
ansible websrvs -m cron -a “minute=/5 job=’/usr/sbin/ntpdate 172.20.0.1 &>/dev/null’ name=Synctime" #创建任务
ansible websrvs -m cron -a "minute=
/5 job=’/usr/sbin/ntpdate 172.20.0.1 &>/dev/null’ name=Synctime disabled=yes” #禁用计划任务
ansible websrvs -m cron -a “minute=/5 job=’/usr/sbin/ntpdate 172.20.0.1 &>/dev/null’ name=Synctime disabled=no" #启用计划任务
ansible websrvs -m cron -a “name=‘backup mysql’ state=absent”
11.Yum模块
管理软件包,只支持RHEL,CentOS,fedora,不支持Ubuntu其它版本
ansible websrvs -m yum -a ‘name=httpd state=present’ #安装
ansible websrvs -m yum -a ‘name=httpd state=absent’ #删除
12.Service模块
管理服务
ansible all -m service -a ‘name=httpd state=started enabled=yes’
ansible all -m service -a ‘name=httpd state=stopped’
ansible all -m service -a ‘name=httpd state=reloaded’
ansible all -m shell -a “sed -i ‘s/^Listen 80/Listen 8080/’ /etc/httpd/conf/httpd.conf”
ansible all -m service -a ‘name=httpd state=restarted’
13.User模块
管理用户
ansible all -m user -a ‘name=user1 comment=“test user” uid=2048 home=/app/user1 group=root’ #创建用户
ansible all -m user -a ‘name=nginx comment=nginx uid=88 group=nginx groups=“root,daemon” shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes’
ansible all -m user -a ‘name=nginx state=absent remove=yes’ #删除用户及家目录等数据
14.Group模块
管理组
ansible websrvs -m group -a ‘name=nginx gid=88 system=yes’ #创建组
ansible websrvs -m group -a ‘name=nginx state=absent’ #删除组
15.Lineinfile模块
相当于sed,可以修改文件内容
ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,存在问题,无法正常进行替换 。其实在ansible自身提供了两个模块:lineinfile模块和replace模块,可以方便的进行替换
ansible all -m lineinfile -a "path=/etc/selinux/config regexp=’^SELINUX=’ line=‘SELINUX=enforcing’"
ansible all -m lineinfile -a ‘path=/etc/fstab state=absent regexp="^#"’
16.Replace模块
该模块有点类似于sed命令,主要也是基于正则进行匹配和替换
ansible all -m replace -a "path=/etc/fstab regexp=’^(UUID.
)’ replace=’#\1’”
ansible all -m replace -a “path=/etc/fstab regexp=’^#(.)’ replace=’\1’"
17.Setup模块
setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,会影响执行速度,可以使用gather_facts: no来禁止 Ansible 收集 facts 信息
ansible all -m setup
ansible all -m setup -a “filter=ansible_nodename”
ansible all -m setup -a “filter=ansible_hostname”
ansible all -m setup -a “filter=ansible_domain”
ansible all -m setup -a “filter=ansible_memtotal_mb”
ansible all -m setup -a “filter=ansible_memory_mb”
ansible all -m setup -a “filter=ansible_memfree_mb”
ansible all -m setup -a “filter=ansible_os_family”
ansible all -m setup -a “filter=ansible_distribution_major_version”
ansible all -m setup -a “filter=ansible_distribution_version”
ansible all -m setup -a “filter=ansible_processor_vcpus”
ansible all -m setup -a “filter=ansible_all_ipv4_addresses”
ansible all -m setup -a “filter=ansible_architecture”
ansible all -m setup -a "filter=ansible_processor

ansible all -m setup -a ‘filter=ansible_python_version’

playbook使用

hosts组件:用于指定要执行任务的主机,须事先定义在主机清单中

  • hosts: websrvs:appsrvs
    remote_user 组件:用于指定远程登陆的用户,也可以通过sudo的方式在远程主机上执行任务,甚至可以在sudo时使用sudo_user指定sudo时切换的用户
- hosts: websrvs
  remote_user: root
  tasks:
    - name: test connection
      ping:
      remote_user: magedu
      sudo: yes                 #默认sudo为root
      sudo_user: wang        #sudo为wang

task列表和action组件:用于指定主机上执行任务,使用指定的参数执行模块,而在模块参数中可以使用变量。模块执行是幂等的,这意味着多次执行是安全的,因为其结果均一致

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

其他组件:某任务的状态在运行后为changed时,可通过“notify”通知给相应的handlers执行,任务还可以通过"tags“打标签,可在ansible-playbook命令上使用-t指定进行调用
Shell Scripts VS Playbook 案例:

#SHELL脚本实现
#!/bin/bash
# 安装Apache
yum install --quiet -y httpd 
# 复制配置文件
cp /tmp/httpd.conf /etc/httpd/conf/httpd.conf
cp/tmp/vhosts.conf /etc/httpd/conf.d/
# 启动Apache,并设置开机启动
systemctl enable --now httpd 
#Playbook实现
- hosts: dbsrvs
  remote_user: root
  gather_facts: no
  tasks:
    - name: "安装Apache"
      yum: name=httpd
    - name: "复制配置文件"
      copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/
    - name: "复制配置文件"
      copy: src=/tmp/vhosts.conf dest=/etc/httpd/conf.d/
    - name: "启动Apache,并设置开机启动"
      service: name=httpd state=started enabled=yes
[root@ansible ~]#cat /data/ansible/install_mysql.yml
---
# install mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz
- hosts: dbsrvs
  remote_user: root
  gather_facts: no
  tasks:
    - name: install packages
      yum: name=libaio,perl-Data-Dumper,perl-Getopt-Long
    - name: create mysql group
      group: name=mysql gid=306 
    - name: create mysql user
      user: name=mysql uid=306 group=mysql shell=/sbin/nologin system=yes create_home=no home=/data/mysql
    - name: copy tar to remote host and file mode 
      unarchive: src=/data/ansible/files/mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz dest=/usr/local/ owner=root group=root 
    - name: create linkfile  /usr/local/mysql 
      file: src=/usr/local/mysql-5.6.46-linux-glibc2.12-x86_64 dest=/usr/local/mysql state=link
    - name: data dir
      shell: chdir=/usr/local/mysql/  ./scripts/mysql_install_db --datadir=/data/mysql --user=mysql
      tags: data
    - name: config my.cnf
      copy: src=/data/ansible/files/my.cnf  dest=/etc/my.cnf 
    - name: service script
      shell: /bin/cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
    - name: enable service
      shell: /etc/init.d/mysqld start;chkconfig --add mysqld;chkconfig mysqld on  
      tags: service
    - name: PATH variable
      copy: content='PATH=/usr/local/mysql/bin:$PATH' dest=/etc/profile.d/mysql.sh
    - name: secure script
      script: /data/ansible/files/secure_mysql.sh
      tags: script

变量
通过{{ variable_name }} 调用变量,且变量名前后建议加空格,有时用“{{ variable_name }}”才生效。
变量来源:

  1. 调用setup模块中的变量
  2. 通过命令行指定变量,优先级最高
ansible-playbook -e varname=value
  1. 在playbook文件中定义
   vars:
     - var1: value1
     - var2: value2
  1. 在独立的变量YAML文件中定义
- hosts: all
     vars_files:
       - vars.yml
  1. 在 /etc/ansible/hosts 中定义
    主机(普通)变量:主机组中主机单独定义,优先级高于公共变量
    组(公共)变量:针对主机组中所有主机定义统一变量
  2. 在role中定义
    使用setup变量:
---
- hosts: all
  remote_user: root
  gather_facts: yes
  tasks:
    - name: create log file
      file: name=/data/{{ ansible_nodename }}.log state=touch owner=wang mode=600

在playbook 命令行中定义变量:

Vim var2.yml
---
- hosts: websrvs
  remote_user: root
  tasks:
    - name: install package
      yum: name={{ pkname }} state=present
ansible-playbook  –e pkname=httpd  var2.yml

使用变量文件:
可以在一个独立的playbook文件中定义变量,在另一个playbook文件中引用变量文件中的变量,比playbook中定义的变量优先级高。

vim vars.yml
---
# variables file
package_name: mariadb-server
service_name: mariadb

vim  var4.yml
---
#install package and start service
- hosts: dbsrvs
  remote_user: root
  vars_files:
    - /root/vars.yml
  tasks:
    - name: install package
      yum: name={{ package_name }}
      tags: install
    - name: start service
      service: name={{ service_name }} state=started enabled=yes

主机清单文件中定义变量:
在inventory 主机清单文件中为指定的主机定义变量以便于在playbook中使用

[websrvs]
www1.magedu.com http_port=80 maxRequestsPerChild=808
www2.magedu.com http_port=8080 maxRequestsPerChild=909

在inventory 主机清单文件中赋予给指定组内所有主机上的在playbook中可用的变量,如果和主机变是同名,优先级低于主机变量

[websrvs]
www1.magedu.com
www2.magedu.com

[websrvs:vars]
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com

vim /etc/ansible/hosts

[websrvs]
192.168.0.101 hname=www1 domain=magedu.io
192.168.0.102 hname=www2 

[websvrs:vars]
mark=“-”
domain=magedu.org

ansible  websvrs  –m hostname –a ‘name={{ hname }}{{ mark }}{{ domain }}bash
#命令行指定变量: 
ansible  websvrs  –e domain=magedu.cn –m hostname –a    ‘name={{ hname }}{{ mark }}{{ domain }}

template模板

template功能:可以根据和参考模块文件,动态生成相类似的配置文件,template文件必须存放于templates目录下,且命名为 .j2 结尾,yaml/yml 文件需和templates目录平级。

[root@ansible ansible]#vim templates/nginx.conf.j2
worker_processes {{ ansible_processor_vcpus**3 }};

[root@ansible ansible]#cat templnginx.yml
---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: install nginx
      yum: name=nginx
    - name: template config to remote hosts
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: restart nginx
    - name: start service
      service: name=nginx state=started enabled=yes

  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

ansible-playbook  templnginx.yml --limit 10.0.0.8

template中使用流程控制 for 和 if:

#templnginx4.yml
- hosts: websrvs
  remote_user: root
  vars:
    nginx_vhosts:
      - listen: 8080
        server_name: "web1.magedu.com"
        root: "/var/www/nginx/web1/"
      - listen: 8081
        server_name: "web2.magedu.com"
        root: "/var/www/nginx/web2/"
      - {listen: 8082, server_name: "web3.magedu.com", root: "/var/www/nginx/web3/"}
  tasks:
    - name: template config 
      template: src=nginx.conf4.j2 dest=/data/nginx4.conf

# templates/nginx.conf4.j2
{% for vhost in nginx_vhosts %}
server {
   listen {{ vhost.listen }}
   server_name {{ vhost.server_name }}
   root {{ vhost.root }}  
}
{% endfor %}

ansible-playbook  templnginx4.yml --limit 10.0.0.8

playbook中使用when:
when语句,可以实现条件测试。如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时要用到条件测试,通过在task后添加when子句即可使用条件测试

---
- hosts: websrvs
  remote_user: root
  tasks: 
    - name: install conf file to centos7
      template: src=nginx.conf.c7.j2 dest=/etc/nginx/nginx.conf
      when: ansible_distribution_major_version == "7"
    - name: install conf file to centos6
      template: src=nginx.conf.c6.j2 dest=/etc/nginx/nginx.conf
      when: ansible_distribution_major_version == "6"
playbook中使用迭代with_items:

迭代:当有需要重复性执行的任务时,可以使用迭代机制,对迭代项的引用,固定变量名为”item“, 要在task中使用with_items给定要迭代的元素列表, 还可以嵌套子变量,关联多个变量在一起使用

cat with_item2.yml
---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: add some groups
      group: name={{ item }} state=present
      with_items:
        - g1
        - g2
        - g3
    - name: add some users
      user: name={{ item.name }} group={{ item.group }} home={{ item.home }} create_home=yes state=present
      with_items:
        - { name: 'user1', group: 'g1', home: '/data/user1' }
        - { name: 'user2', group: 'g2', home: '/data/user2' }
        - { name: 'user3', group: 'g3', home: '/data/user3' }

role使用

角色是ansible自1.2版本引入的新特性,用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲,roles就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中,并可以便捷地include它们的一种机制。角色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中
Roles各目录作用:
roles/project/ :项目名称,有以下子目录
files/ :存放由copy或script模块等调用的文件
templates/:template模块查找所需要模板文件的目录
tasks/:定义task,role的基本元素,至少应该包含一个名为main.yml的文件;其它的文件需要在此文件中通过include进行包含
handlers/:至少应该包含一个名为main.yml的文件;其它的文件需要在此文件中通过include进行包含
vars/:定义变量,至少应该包含一个名为main.yml的文件;其它的文件需要在此文件中通过include进行包含
meta/:定义当前角色的特殊设定及其依赖关系,至少应该包含一个名为main.yml的文件,其它文件需在此文件中通过include进行包含
default/:设定默认变量时使用此目录中的main.yml文件,比vars的优先级低
创建role的步骤:
(1) 创建以roles命名的目录
(2) 在roles目录中分别创建以各角色名称命名的目录,如webservers等
(3) 在每个角色命名的目录中分别创建files、handlers、meta、tasks、templates和vars目录;用不到的目录可以创建为空目录,也可以不创建
(4) 在playbook文件中,调用各角色
playbook调用角色:

---
- hosts: websrvs
  remote_user: root
  roles:
    - mysql
    - memcached
    - nginx  

键role用于指定角色名称,后续的k/v用于传递变量给角色

---
- hosts: all
  remote_user: root
  roles:
    - mysql
    - { role: nginx, username: nginx }

还可基于条件测试实现角色调用

---
- hosts: all
  remote_user: root
  roles:
    - { role: nginx, username: nginx, when: ansible_distribution_major_version == ‘7’  }
roles 中 tags 使用:
#nginx-role.yml
---
- hosts: websrvs
  remote_user: root
  roles:
    - { role: nginx ,tags: [ 'nginx', 'web' ] ,when: ansible_distribution_major_version == "6“ }
    - { role: httpd ,tags: [ 'httpd', 'web' ]  }
    - { role: mysql ,tags: [ 'mysql', 'db' ] }
    - { role: mariadb ,tags: [ 'mariadb', 'db' ] }

ansible-playbook --tags="nginx,httpd,mysql" nginx-role.yml

案例:
实现httpd角色

#相关的目录
mkdir -pv /data/ansible/roles/httpd/{tasks,handlers,files}

#创建角色相关的文件
cd /data/ansible/roles/httpd/

vim tasks/main.yml
- include: group.yml
- include: user.yml
- include: install.yml
- include: config.yml
- include: index.yml
- include: service.yml

vim  tasks/user.yml
- name: create apache user
  user: name=apache system=yes shell=/sbin/nologin home=/var/www/ uid=80 group=apache

vim  tasks/group.yml
- name: create apache group
  group: name=apache system=yes gid=80

vim tasks/install.yml
- name: install httpd package
  yum: name=httpd

vim tasks/config.yml
- name: config file
  copy: src=httpd.conf dest=/etc/httpd/conf/ backup=yes
  notify: restart

vim tasks/index.yml
- name: index.html
  copy: src=index.html dest=/var/www/html/

vim tasks/service.yml
- name: start service
  service: name=httpd state=started enabled=yes

vim handlers/main.yml
- name: restart
  service: name=httpd state=restarted

#在files目录下准备两个文件
ls files/
httpd.conf index.html

tree /data/ansible/roles/httpd/
/data/ansible/roles/httpd/
├── files
│   ├── httpd.conf
│   └── index.html
├── handlers
│   └── main.yml
└── tasks
    ├── config.yml
    ├── group.yml
    ├── index.yml
    ├── install.yml
    ├── main.yml
    ├── service.yml
    └── user.yml

3 directories, 10 files

#在playbook中调用角色
vim  /data/ansible/role_httpd.yml
---
# httpd role
- hosts: websrvs
  remote_user: root

  roles:
    - httpd

#运行playbook
ansible-playbook  /data/ansible/role_httpd.yml

实现nginx角色

mkdir -pv  /data/ansible/roles/nginx/{tasks,handlers,templates,vars}

#创建task文件
cd /data/ansible/roles/nginx/

vim tasks/main.yml 
- include: install.yml
- include: config.yml
- include: index.yml
- include: service.yml

vim  tasks/install.yml 
- name: install
  yum: name=nginx 

vim tasks/config.yml 
- name: config file for centos7
  template: src=nginx7.conf.j2 dest=/etc/nginx/nginx.conf
  when: ansible_distribution_major_version=="7"
  notify: restart
- name: config file for centos8
  template: src=nginx8.conf.j2 dest=/etc/nginx/nginx.conf
  when: ansible_distribution_major_version=="8"
  notify: restart

vim  tasks/index.yml 
- name: index.html
  copy: src=roles/httpd/files/index.html dest=/usr/share/nginx/html/

vim tasks/service.yml 
- name: start service
  service: name=nginx state=started enabled=yes

#创建handler文件
cat handlers/main.yml 
- name: restart
  service: name=nginx state=restarted

#创建两个template文件
cat templates/nginx7.conf.j2
...省略...
user {{ user }};
worker_processes {{ ansible_processor_vcpus+3 }};   #修改此行
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
...省略...

cat templates/nginx8.conf.j2
...省略...
user nginx;
worker_processes {{ ansible_processor_vcpus**3 }};  #修改此行
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
...省略...

#创建变量文件
vim vars/main.yml 
user: daemon

#目录结构如下

tree /data/ansible/roles/nginx/
/data/ansible/roles/nginx/
├── handlers
│   └── main.yml
├── tasks
│   ├── config.yml
│   ├── file.yml
│   ├── install.yml
│   ├── main.yml
│   └── service.yml
├── templates
│   ├── nginx7.conf.j2
│   └── nginx8.conf.j2
└── vars
    └── main.yml

4 directories, 9 files

#在playbook中调用角色
vim /data/ansible/role_nginx.yml 
---
#nginx role 
- hosts: websrvs

  roles:
    - role: nginx

#运行playbook
ansible-playbook  /data/ansible/role_nginx.yml

实现多角色的选择

vim /data/ansible/role_httpd_nginx.yml 
---
- hosts: websrvs

  roles:
    - {role: httpd,tags: [httpd,web], when: ansible_distribution_major_version=="7" }
    - {role: nginx,tags: [nginx,web], when: ansible_distribution_major_version=="8" }

标题管理节点过多导致的超时问题

默认情况下,Ansible将尝试并行管理playbook中所有的机器。对于滚动更新用例,可以使用serial关键字定义Ansible一次应管理多少主机,还可以将serial关键字指定为百分比,表示每次并行执行的主机数占总数的比例

#vim test_serial.yml
---
- hosts: all
  serial: 2  #每次只同时处理2个主机
  gather_facts: False
  tasks:
    - name: task one
      comand: hostname
    - name: task two
      command: hostname
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值