设为首页 收藏本站
查看: 1339|回复: 0

[经验分享] ansible-Astrotrain

[复制链接]

尚未签到

发表于 2018-7-29 14:34:32 | 显示全部楼层 |阅读模式
Ansible
一、运维工具的分类
agent:基于专用的agent程序完成管理功能,puppet, func, zabbix, ...  
agentless:基于ssh服务完成管理,ansible, fabric, ...
1、什么是ansible
ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。仅需在管理工作站上安装ansible程序配置被管控主机的IP信息,被管控的主机无客户端。ansible应用程序存在于epel(第三方社区)源,依赖于很多python组件。ansible是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。
参考站点:http://www.ansible.com.cn
2、ansible架构
Ansible Core:ansible自身核心模块  
Modules:
  
    Core Modules:自带模块
  
    Customed Modules:自定义模块
  
Host Iventory 主机清单,定义可管控的主机列表
  
    Files:;通过配置文件定义
  
    CMDB:使用外部存储装载要管理的主机来定义
  
PlayBooks:剧本,把需要完成的多个任务定义在剧本中
  
    Hosts:定义的剧本角色
  
    roles:定义好的任务功能由角色来完成
  
Connection Plugins:连接插件
  
    ansible基于连接插件连接到各个主机上,虽然ansible是使用ssh连接到各个主机的,但是它还支持其他的连接方法,所以需要有连接插件,尤其是要完成并发连接
DSC0000.png

3、ansible特性
模块化设计,调用特定的模块来完成特定任务,本身是核心组件,短小精悍;  
基于Python语言实现,由Paramiko(python的一个可并发连接ssh主机功能库), PyYAML和Jinja2(模板化)三个关键模块实现;
  
不需要在被管理节点上安装客户端,只要有sshd即可,部署非常简单
  
支持自定义模块,使用任意编程语言;
  
强大的playbook机制;
  
幂等性;
ansible的安装和使用
ansible无服务器端,使用时直接运行命令即可,同时不需要在被管控主机上安装任何客户端,因此ansible是一个十分轻量级的工具,可以在epel源进行安装,ansible已经被红帽收购,相信不久会被收入base源配置好epel源后直接yum安装ansible
DSC0001.png

DSC0002.png

3.1、程序环境及主要配置文件
程序:  
    ansible
  
    ansible-playbook
  
    ansible-doc
  
配置文件:
  
    /etc/ansible/ansible.cfg
  
主机清单:
  
    /etc/ansible/hosts
  
插件目录:
  
    /usr/share/ansible_plugins/
  
配置Host Inventory示例:
  
    ]# cp hosts{,.bak}先做备份
  
    # Ex 1: Ungrouped hosts, specify before any group headers.直接在任何组的头部前面指定,不属于任何组的主机
  
        green.example.com
  
        blue.example.com
  
        192.168.100.1
  
        192.168.100.10
  
    # Ex 2: A collection of hosts belonging to the 'webservers' group一批主机属于一个组,例如定义为'webservers'的组,且一个主机可以属于多个组
  
        [webservers]
  
        alpha.example.org
  
        beta.example.org
  
        192.168.1.100
  
        192.168.1.110
二、ansible应用程序命令格式
1.ansible-doc命令:获取模块列表,及模块使用格式;
ansible-doc -l:获取列表  
ansible-doc -s  module_name:获取指定模块的使用信息
2.命令格式
ansible  <host-pattern>  [-f forks] [-m module_name]  [-a args]  
    <host-pattern> :指明管控主机,以模式形式表示或者直接给定IP,必须事先定义在文件中;all设置所有
  
                    <host-pattern>默认读取/etc/ansible/hosts,也可以指明自定义文件路径
  
                    -iPATH, --inventory=PATH:指明使用的host inventory文件路径;
  
    [-f forks] :指明每批管控多少主机,默认为5个主机一批次
  
    [-m module_name] :使用何种模块管理操作,所有的操作都需要通过模块来指定
  
    [-a args] :指明模块专用参数;args一般为key=value格式
  
                注意:command模块的参数非为kv格式,而是直接给出要执行的命令即可;
  
常用选项
  
    -m MOD_NAME  -a MOD_ARGS
3.ansible的连接:
  通过前面的介绍我们知道,ansible是基于ssh协议来进行数据传输,ssh连接一般有两种方法,一种是使用密码密钥,一种是使用公私密码免密码登录,为了顺利使用ansible,下面配置基于公私密码免密码登录
1)生成密钥对  
    [root@localhost]# ssh-keygen -t rsa
  
        #-t表示使用的加密类型,其中rsa1表示version1版本,rsa、dsa、ecdsa的加密对于的是version2版本
  
    Generating public/private rsa key pair.
  
        #这里询问你要把生成的密钥文件保存在哪里,默认是在家目录下的.ssh文件夹中,回车保存默认目录
  
    Enter file in which to save the key (/root/.ssh/id_rsa):
  
        #这里是对密钥文件加密,不输入则表示不加密
  
    Enter passphrase (empty for no passphrase):
  
    Enter same passphrase again:
  

  
2)查看已经成功生成了一对密钥
  
    [root@localhost ~]# ls /root/.ssh
  
    id_rsa  id_rsa.pub#其中id_rsa为私钥,id_rsa.pub为公钥
  

  
3)在生成完密钥对之后将公钥上传给服务器对应用户的家目录
  
    [root@localhost ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.25.139
  
    [root@localhost ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.25.140
  
    [root@localhost ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.25.141
  

  
4)配置ansible需要控制的主机列表,其配置在hosts文件中:
  
    [websrvs]
  
    192.168.25.139
  

  
    [dbsrvs]
  
    192.168.25.140
  
    192.168.25.141
3.1inventory参数:主机库ssh参数设置
  ansible基于ssh连接inventory中指定的远程主机时,将以此处的参数指定的属性进行;
ansible_ssh_port:指定ssh端口  
ansible_ssh_user:指定ssh用户
  
ansible_ssh_pass:指定ssh用户登录是认证密码,明文密码不安全
  
ansible_sudo_pass:指明sudo时候的密码
  
示例:
  
    [websrvs]
  
    192.168.25.139  ansible_ssh_port=22  ansible_ssh_user=root  ansible_ssh_pass=ali
  
    192.168.25.140
  
注意:在/etc/ansible/hosts中直接定义连接时候的密码不安全,一般建议基于ssh的密钥认证方式实现
4.常用模块
  1)ping:探测目标主机是否存活;
[root@localhost ~]# ansible websrvs -m ping #指定一个主机组进行探测  
[root@localhost ~]# ansible all -m ping #探测所有主机
  2)command:默认模块,可省略。在远程主机上进行操作命令
  -a 'COMMAND'
[root@localhost ~]# ansible all -m command -a "ifconfig"  
[root@localhost ~]# ansible all -a "ifconfig"
  3)shell:在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等 ;
  -a 'COMMAND' 运行shell命令
[root@localhost ~]# ansible all -m shell -a "echo '1' |passwd --stdin root"注意:command和shell模块的核心参数直接为命令本身;而其它模块的参数通常为“key=value”格式;
  4)copy:复制文件到远程主机
  用法:(1) 复制文件 -a "src= dest= "(2) 给定内容生成文件 -a "content= dest= "
[root@localhost ~]# ansible all -m copy -a "src=/etc/fstab dest=/tmp/fstab.ansible mode=640"  
[root@localhost ~]# ansible all -m copy -a "content=hello\nmyali\n dest=/tmp/myali.ansible mode=640"
  5)file:文件管理
  用法:(1) 创建目录:-a "path= state=directory" (2) 创建链接文件:-a "path= src= state=link" (3) 删除文件:-a "path= state=absent“
[root@localhost ~]# ansible all -m file -a "path=/tmp/fstab.ansible owner=centos"  
[root@localhost ~]# ansible all -m file -a "path=/tmp/fstab.ansible state=absent"
  
[root@localhost ~]# ansible all -m file -a "path=/tmp/dir.ansible state=directory"
  
[root@localhost ~]# ansible all -m file -a "path=/tmp/test.ansible.link src=/tmp/test.ansible state=link"
  6)cron:管理周期性计划任务
  用法:-a ' minute= hour= day= month= weekday= job= name= user= state={present|absent}'
[root@localhost ~]# ansible all -m cron -a "minute='*/5' job='/usr/sbin/ntpdate 192.168.15.128 &> /dev/null' name='sync time'"  
[root@localhost ~]# ansible all -m cron -a "name='sync time' state=absent"
  7)hostname:设置主机名
  用法:name=
  8)yum:使用yum包管理器完成程序包管理
  用法:(1) -a "name= state={present|latest}" 安装程序包,(2) -a "name= state=absent" 删除程序包
[root@localhost ~]# ansible all -m yum -a "name=httpd"  
[root@localhost ~]# ansible all -m yum -a "name=httpd state=absent"
  9)service:控制服务
  用法:-a 'name= state={started|stopped|restarted} enabled=(是否开机自动启动) runlevel='
[root@localhost ~]# ansible all -m service -a "name=httpd state=started enabled=true"  10)group:添加或删除组
  用法:-a 'name= state={present|absent} gid= system=(系统组)'
[root@localhost ~]# ansible all -m group -a 'name=mygroup state=present system=true'  11)user:管理组帐号
  用法:-a 'name= state={present(创建)|absent(删除)} force=(是否强制操作删除家目录) system= uid= shell= home='
[root@localhost ~]# ansible all -m user -a 'name=ansible state=present'  12)script:运行脚本
  用法:-a '/PATH/TO/SCRIPT'运行脚本
[root@localhost ~]# ansible all -m script -a '/tmp/a.sh'  13)setup:获取指定主机的facts变量;
[root@localhost ~]# ansible 192.168.25.139 -m setup三、Playbooks剧本
  playbooks是ansible更强大的配置管理组件,实现基于文本文件编排执行的多个任务,且多次重复执行
1.playbook组织格式:YAML语言格式
  YAML类似于半结构化数据,声明式配置;可读性较高的用来表达资料序列的格式,易于与脚本语言交互
2.语法格式
  1)任何数据结构都用缩进来标识,可以嵌套
  2)每一行是一个键值数据key:value,冒号隔开。若想在一行标识需要用{ }和,分隔格式
  3)列表用 – 标识
3Playbook
  1)核心元素
Tasks:任务,由模块定义的操作的列表;  
Variables:变量
  
Templates:模板,即使用了模板语法的文本文件;
  
Handlers:处理器,由特定条件触发的Tasks;
  
Roles:角色;由多个自包含的完整的Tasks,Variables,Templates,Handlers...等等组成的操作的集合
  2)基础组件:
Hosts:运行指定任务的目标主机;  
remote_user:在远程主机以哪个用户身份执行;
  
    sudo_user:非管理员需要拥有sudo权限;
  
tasks:任务列表
  
    列表由模块,模块参数组成如下:
  
        格式:
  
            (1) action: module arguments
  
            (2) module: arguments
  3)playbook定义任务: playbook的存储在*.yaml文本中,需要创建一个yaml文件
- name: task description   注释描述信息  

  
module_name: module_args   声明模块:定义ansible模块参数
DSC0003.png

  4)ansible-playbook执行命令:
(1) 检测语法  
    ansible-playbook  --syntax-check  /path/to/playbook.yaml
  
(2) 测试运行
  
    ansible-playbook -C /path/to/playbook.yaml
  
        --list-hosts
  
        --list-tasks
  
        --list-tags
  
    [root@localhost ~]# ansible-playbook  --check --list-hosts --list-tasks group.yaml
  
(3) 运行
  
    ansible-playbook  /path/to/playbook.yaml
  
        -t TAGS, --tags=TAGS:只运行标记了的任务
  
        --skip-tags=SKIP_TAGS:跳过指定的标签所标记的任务
  
        --start-at-task=START_AT:从指定的任务开始向后 运行
  5)playbook---Variables 变量
1)变量命名:字母、数字和下划线组成,仅能以字母开头;  
2)变量类型
  
    内建:
  
        1) facts:由远程主机发回的主机特有的属性信息,这些信息被保存在ansible变量中;无须声明,可直接调用;
  
    自定义变量:
  
        1) 命令行传递;ansible-playbook  test.yml  --extra-vars "host=www user=test"
  
        2) 在hosts Inventory中为每个主机定义专用变量值;
  
            a) 向不同的主机传递不同的变量 ;
  
                [websrvs]
  
                192.168.25.139    host=mail
  
                192.168.25.140
  
                192.168.25.141
  
            b) 向组内的所有主机传递相同的变量 ;
  
                [groupname:vars]
  
                variable_name=value
  
                注意:组名要事先存在,实例如下:
  
                    [websrvs]
  
                    192.168.25.139
  
                    192.168.25.140
  
                    [websrvs:vars]
  
                    host=mail
  
        3) 在playbook中定义
  
            vars:
  
            - var_name: value
  
            - var_name: value
  

  
        4) 在角色调用时传递
  
            roles:
  
            - { role: ROLE_NAME, var: value, ...}
  

  
3)变量调用:
  
    {{ var_name }}
  6)Templates:模板
  文本文件,内部嵌套有模板语言脚本(使用模板语言编写)模板文件中可使用jinja2表达式,表达式要定义在{{}},也可以简单地仅执行变量替换;
  语法:
字面量:  
    字符串:使用单引号或双引号;
  
    数字:整数、浮点数;
  
    列表:[item1, item2, ...]
  
    元组:(item1, item2, ...)
  
    字典:{key1:value1, key2:value2, ...}
  
    布尔型:true/false
  

  
算术运算:
  
    +, -, *, /, //, %, **
  

  
比较操作:
  
    ==, !=, >, <, >=, <=
  

  
逻辑运算:and, or, not
  

  
执行模板文件中的脚本,并生成结果数据流,需要使用template模块;
  
template模块格式:
  
    -a ”“
  
    src=
  
    dest=
  
    mode=
  
    onwer=
  
    group=
  
    注意:此模板不能在命令行使用,而只能用于playbook;
  

  
定义方法:
  
    步骤1:在本地的nginx配置文件中写入fact变量名称
  
    步骤2:在yam文件中使用template模版将nginx配置文件复制到远程主机,并且模版文件要以.j2结尾
  
    步骤3:执行ansible-playbook xxx.yaml命令,
  
    步骤4:在远程主机上测试查看配置文件中的变量名称传递过去的是否有值
  
示例:见后方;
  7)条件测试
  在某task后面添加when子句即可实现条件测试功能;when语句支持Jinja2语法;
  有的时候在特定的主机需要跳过特定的步骤,例如在安装包的时候,需要指定主机的操作系统类型,或者是当操作系统的硬盘满了之后,需要清空文件等,可以使用when语句来做判断 。when关键字后面跟着的是python的表达式,在表达式中你能够使用任何的变量或者fact,当表达式的结果返回的是false,便会跳过本次的任务
  示例:当系统版本是centos6和7时各使用不同的命令
- hosts: all  
  remote_user: root
  
  tasks:
  
  - name: install nginx package
  
    yum: name=nginx state=latest
  
  - name: start nginx service6
  
    shell: service ngixn start
  
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"
  
  - name: start nginx service
  
    shell: systemctl start ngixn.service
  
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
  8)循环:迭代,需要重复执行的任务;在task中调用内置的item变量;在某task后面使用with_items语句来定义元素列表;
  元素:列表有两种方式; 字符串和字典
  循环迭代:基于字符串列表给出元素示例:
[root@localhost ~]# vim websrvs.yaml  
    - hosts: websrvs
  
      remote_user: root
  
      tasks:
  
      - name: install packages
  
        yum: name={{ item  }} state=latest
  
        with_items:
  
        - httpd
  
        - php
  
        - php-mysql
  
        - php-mbstring
  
        - php-gd
  循环迭代:基于字典列表给元素示例:
[root@localhost ~]# vim users.yaml  
- hosts: all
  
  remote_user: root
  
  tasks:
  
  - name: create groups
  
    group: name={{ item }} state=present
  
    with_items:
  
    - groupx1
  
    - groupx2
  
    - groupx3
  
  - name: create users
  
    user: name={{ item.name }} group={{ item.group }} state=present
  
    with_items:
  
    - {name: 'userx1', group: 'groupx1'}
  
    - {name: 'userx2', group: 'groupx2'}
  
    - {name: 'userx3', group: 'groupx3'}
  9)roles:角色
  当单个playbook文件越来越大的时候,我们就需要重新来组织Playbooks了。我们可以将一个大的playbook拆成若干个小的 playbook文件,然后通过include的方式,在主配置文件中将这些零碎的小文件包含进来,这叫做playbook的包含。我们也可以按照一定的 规则将执行的某一类型任务放在一个目录里,并在这个目录中再次对这个playbook按照 tasks,handlers,files,templates,vars等类型划分成若干文件,将对应文件存放在对应的目录中,这种组织方式就叫做 playbook的roles。
  以特定的层级目录结构进行组织的tasks、variables、handlers、templates、files等;
  role_name/
  files/:存储由copy或script等模块调用的文件; tasks/:此目录中至少应该有一个名为main.yml的文件,用于定义各task;其它的文件需要由main.yml进行“包含”调用; handlers/:此目录中至少应该有一个名为main.yml的文件,用于定义各handler;其它的文件需要由main.yml进行“包含”调用; vars/:此目录中至少应该有一个名为main.yml的文件,用于定义各variable;其它的文件需要由main.yml进行“包含”调用; templates/:存储由template模块调用的模板文本; meta/:此目录中至少应该有一个名为main.yml的文件,定义当前角色的特殊设定及其依赖关系;其它的文件需要由main.yml进行“包含”调用; default/:此目录中至少应该有一个名为main.yml的文件,用于设定默认变量;
  在playbook中调用角色的方法: - hosts: HOSTS remote_user: USERNAME roles: - ROLE1 - ROLE2 - { role: ROLE3, VARIABLE: VALUE, ...} - { role: ROLE4, when: CONDITION }
5.playboot示例
  1)基础示例
[root@localhost ~]# vim group.yaml  
[root@localhost ~]# cat group.yaml
  
- hosts: all
  
   remote_user: root
  
   tasks:
  
   - name: install a group
  
     group: name=mygrp system=true
  
   - name: install a user
  
     user: name=user1 group=mygrp system=true
  

  
- hosts: websrvs
  
   remote_user: root
  
   tasks:
  
   - name: install httpd package
  
     yum: name=httpd
  
   - name: start httpd service
  
     service: name=httpd state=started
  正式使用时我们最好先预运行下看有没有错误
[root@localhost ~]# ansible-playbook --check group.yaml  没有问题就可以正式运行命令脚本了
[root@localhost ~]# ansible-playbook  group.yaml
DSC0004.png

  2)handlers:由特定条件触发的Tasks;
  只有其关注的条件满足时,才会被触发执行的任务;
  调用及定义方式:
tasks:  
  - name: TASK_NAME
  
  module: arguments
  
  notify: HANDLER_NAME
  
handlers:
  
  - name: HANDLER_NAME
  
  module: arguments
  handlers示例:
- hosts: websrvs  
remote_user: root
  
tasks:
  
- name: install httpd package
  
  yum: name=httpd state=latest
  
- name: install conf file
  
  copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
  
  notify: reload httpd service
  
- name: start httpd service
  
  service: name=httpd state=started
  
handlers:
  
- name: reload httpd service
  
  shell: /usr/sbin/httpd reload
  

  
    修改Listen 80为Linsten 8080:
  
[root@localhost ~]# ansible-playbook --check web.yaml
  
[root@localhost ~]# ansible-playbook web.yaml
DSC0005.png

  3)tags:给指定的任务定义一个调用标识;
- name: NAME  
module: arguments
  
tags: TAG_ID
  tags示例:
- hosts: websrvs  
  remote_user: root
  
  tasks:
  
  - name: install httpd package
  
    yum: name=httpd state=latest
  
  - name: install conf file
  
    copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
  
    tags: instconf
  
    notify: reload httpd service
  
  - name: start httpd service
  
    service: name=httpd state=started
  
  handlers:
  
  - name: reload httpd service
  
    shell: service httpd reload
  

  
[root@localhost ~]# ansible-playbook --check -t instconf web.yaml
  

  
[root@localhost ~]# ansible-playbook -t instconf web.yaml
DSC0006.png

DSC0007.png

注意:多个任务可以使用同一个tags,也可以一次任务指多个tags,执行命令时多个tags用,号隔开;如下图  

  
[root@localhost ~]# ansible-playbook -t instconf,instpkg web.yaml
DSC0008.png

DSC0009.png

  4)variables示例(1)
- hosts: websrvs  
  remote_user: root
  
  vars:
  
  - pkgname: vsftpd
  
  tasks:
  
  - name: install a package
  
    yum: name={{ pkgname }} state=present
  

  
[root@localhost ~]# ansible-playbook  pkg.yaml 直接执行yaml脚本,安装的是剧本中定义的变量
  

  
[root@localhost ~]# ansible-playbook  -e pkgname=memcached pkg.yaml 注意:命令行变量的优先于剧本中定义的值
DSC00010.png

  4)variables示例(2):向不同的系统传递不同的变量
  编辑剧本
- hosts: websrvs  
  remote_user: root
  
  tasks:
  
  - name: install a package
  
    yum: name={{ pkgname }} state=present
  编辑hosts文件,将变量赋值到hosts对应的主机后,实现不同主机安装不同的程序包
[websrvs]  
192.168.25.139 pkgname=nginx
  
192.168.25.140 pkgname=httpd
  4)variables示例(3):在hosts文件中向一个主机组赋值变量
[websrvs]  
192.168.25.139
  
192.168.25.140
  

  
[websrvs:vars]
  
pkgname=memcached
  

  
[dbsrvs]
  
192.168.25.141
  5)Templates:模板;示例1
  第一步:ansible主机编辑配置文件作为要使用templates传递的文件;以nginx的配置文件中的cpu核心数为例
[root@localhost ~]# vim  /root/nginx.conf.j2  

  
#user  nobody;
  
worker_processes  {{ ansible_processor_vcpus }};
  第二步:编辑playbook调用templates模块
[root@localhost ~]# vim test.yaml  

  
- hosts: websrvs
  
  remote_user: root
  
  tasks:
  
  - name: genrrate conf file
  
    template: src=/root/nginx.conf.j2 dest=/tmp/nginx.conf
  第三步:执行playbook命令
[root@localhost ~]# ansible-playbook  test.yaml  第四步:在对应的被管控主机上查看配置文件中的变量是否是响应的值
[root@localhost ~]# less /tmp/nginx.conf  

  
#user  nobody;
  
worker_processes  1;
  5)Templates:模板;示例2:定义一个名为nginx.yaml的模版剧本,完成安装nginx程序包,复制配置文件,启动服务,定义tags通知处理器完成服务重载
  第一步:在ansible主机的/etc/ansible/hosts文件中定义一个nginx组
[nginx]  
192.168.25.139
  
192.168.25.140
  第二步:写一个nginx专用的yaml文件,注意:在安装程序包的时候依赖与远程主机的yum源,如果没有yum源的话,可以使用shell模块让远程主机先下载一个程序包,然后再执行后续的安装任务,在安装任务时指明yum: name=绝对路径来进行
- hosts: nginx  
  remote_user: root
  
  tasks:
  
  - name: install nginx package
  
    yum: name=nginx state=latest
  
  - name: install conf file
  
    template: src=/root/nginx.conf.j2 dest=/etc/nginx/nginx.conf
  
    tags: ngxconf
  
    notify: reload nginx service
  
  - name: start nginx service
  
    service: name=nginx state=started enabled=true
  
  handlers:
  
  - name: reload nginx service
  
    shell: /usr/sbin/nginx -s reload
  第三步:提供一个.j2结尾的nginx配置文件,里边写上自己需要的配置
[root@localhost ~]# vim nginx.conf.j2  第四步:执行ansible-playbook命令,运行nginx.yaml
[root@localhost ~]# ansible-playbook --check nginx.yaml  注意:测试运行的时候因为远程主机没有安装程序包,所以在执行到第三个任务时会出错,没有影响,直接运行就可以了  

  
[root@localhost ~]# ansible-playbook  nginx.yaml
  第五步:在远程主机查看是否生效
  6)循环迭代:基于字符串列表给出元素示例:
[root@localhost ~]# vim websrvs.yaml  
    - hosts: websrvs
  
      remote_user: root
  
      tasks:
  
      - name: install packages
  
        yum: name={{ item  }} state=latest
  
        with_items:
  
        - httpd
  
        - php
  
        - php-mysql
  
        - php-mbstring
  
        - php-gd
  7)循环迭代:基于字典列表给元素示例:
[root@localhost ~]# vim users.yaml  
- hosts: all
  
  remote_user: root
  
  tasks:
  
  - name: create groups
  
    group: name={{ item }} state=present
  
    with_items:
  
    - groupx1
  
    - groupx2
  
    - groupx3
  
  - name: create users
  
    user: name={{ item.name }} group={{ item.group }} state=present
  
    with_items:
  
    - {name: 'userx1', group: 'groupx1'}
  
    - {name: 'userx2', group: 'groupx2'}
  
    - {name: 'userx3', group: 'groupx3'}
  8)roles示例nginx
cd到ansible角色目录  
[root@localhost ~]# cd /etc/ansible/roles/
  

  

  
创建角色和各角色下的目录
  
[root@localhost roles]# mkdir ./{nginx,memcached,httpd,mysql}/{files,templates,vars,handlers,meta,default,tasks} -pv
  

  

  
为nginx/files/目录下提供nginx的rpm包
  
lftp 10.1.0.1:/pub/Sources/6.x86_64/nginx> mget nginx-1.6.2-1.el6.ngx.x86_64.rpm
  

  
安装nginx程序 只为了拷贝配置文件
  
[root@localhost nginx]# yum install files/nginx-1.6.2-1.el6.ngx.x86_64.rpm
  

  
编辑nginx的tasks
  
[root@localhost roles]# vim  nginx/tasks/main.yml
  
    - name: copy nginx package to remote host
  
      copy: src=nginx-1.6.2-1.el6.ngx.x86_64.rpm dest=/tmp/nginx-1.6.2-1.el6.ngx.x86_64.rpm
  
    - name: install nginx package
  
      yum: name=/tmp/nginx-1.6.2-1.el6.ngx.x86_64.rpm state=present
  
    - name: install conf file nginx.conf
  
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  
      tags: ngxconf
  
      notify: reload nginx service
  
    - name: start nginx service
  
      service: name=nginx enabled=true state=started
  
    - name: install conf file default.conf
  
      template: src=default.conf.j2 dest=/etc/nginx/conf.d/default.conf
  
      tags: ngxconf
  
      notify: reload nginx service
  

  

  
编辑nginx的handlers
  
[root@localhost roles]# vim nginx/handlers/main.yml
  
    - name: reload nginx service
  
      service: name=nginx state=restarted
  

  
为nginx提供配置文件这里直接复制本机的配置文件做修改
  
[root@localhost roles]# cp /etc/nginx/nginx.conf nginx/templates/nginx.conf.j2
  
[root@localhost roles]# vim nginx/templates/nginx.conf.j2
  
    user  nginx;
  
    worker_processes  {{ ansible_processor_vcpus }};注意cpu可以减1 或者减2 如: {{ ansible_processes_vcpus - 1 }};
  
[root@localhost nginx]# cp /etc/nginx/conf.d/default.conf templates/default.conf.j2
  
[root@localhost nginx]# vim templates/default.conf.j2
  
    server {
  
        listen       {{ ngxport }};
  
        server_name  localhost;
  

  
编辑nginx的变量
  
[root@localhost nginx]# vim vars/main.yml
  
    ngxport: "8090" 这里定格写
  

  
编辑调用角色的配置文件:
  
[root@localhost ansible]# vim /etc/ansible/nginx.yml
  
    - hosts: nginx
  
      remote_user: root
  
      roles:
  
      - nginx
  

  
编辑ansible的配置文件,启用roles寻找路径
  
[root@localhost ~]# vim /etc/ansible/ansible.cfg
  
    36 roles_path    = /etc/ansible/roles
  

  
测试运行
  
[root@localhost ansible]# ansible-playbook --check nginx.yml
  

  
没有问题就可以直接运行了
  
[root@localhost ansible]# ansible-playbook  nginx.yml
  

  
执行成功以后就可以在其他主机上测试了
  
[root@localhost ~]# ss -tnl
  
    8090端口处于监听状态
  

  
现在再次让nginx监听到8080端口;
  
编辑nginx.yml配置文件
  
[root@localhost ansible]# vim nginx.yml
  
- hosts: nginx
  
remote_user: root
  
roles:
  
- { role: nginx, ngxport: 8080 }
  

  
执行命令:指明标签跳过其他任务只执行ngxconf标签
  
[root@localhost ansible]# ansible-playbook -t ngxconf nginx.yml
  

  
在远程主机上查看监听端口,已经是8080了
  
    ]# ss -tnl
  8)relos示例memcached
[root@localhost ansible]# yum install memcached -y  

  
[root@localhost ansible]# vim roles/memcached/tasks/main.yml
  
    - name: install memcached
  
      yum: name=memcached state=latest
  
    - name: install conf file
  
      template: src=memcached.j2 dest=/etc/sysconfig/memcached
  
      tags: mcconf
  
      notify: reload memcached
  
    - name: start memcached service
  
      service: name=memcached state=started enabled=true
  

  
[root@localhost ansible]# vim roles/memcached/handlers/main.yml
  
    - name: reload memcached
  
      service: name=memcached state=restarted
  

  
[root@localhost ansible]# cp /etc/sysconfig/memcached roles/memcached/templates/memcached.j2
  

  
[root@localhost ansible]# vim roles/memcached/templates/memcached.j2
  
    PORT="11211"
  
    USER="memcached"
  
    MAXCONN="1024"
  
    CACHESIZE="{{ ansible_memtotal_mb // 4 }}"
  
    OPTIONS=""
  

  
[root@localhost ansible]# vim nginx.yml
  
    - hosts: nginx
  
      remote_user: root
  
      roles:
  
      - nginx
  
      - memcached
  
[root@localhost ansible]# ansible-playbook nginx.yml
  
[root@localhost ~]# cat /etc/sysconfig/memcached 远程主机查看内存大小
  
PORT="11211"
  
USER="memcached"
  
MAXCONN="1024"
  
CACHESIZE="245"
  
OPTIONS=""
  8)relos示例mysqk
[root@localhost ansible]# vim roles/mysql/tasks/main.yml  
    - name: install mysql-server
  
      yum: name=mysql-server state=latest
  
      when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"
  
    - name: install mariadb-server
  
      yum: name=mysql-server state=latest
  
      when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
  
    - name: start mysql service
  
      service: name=mysqld state=started
  
      when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"
  
    - name: start mariadb service
  
      service: name=mariadb state=started
  
      when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
  

  
[root@localhost ansible]# vim db.yml
  
    - hosts: dbsrvs
  
      remote_user: root
  
      roles:
  
      - mysql
  

  
[root@localhost ansible]# ansible-playbook  db.yml

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-543167-1-1.html 上篇帖子: ansible-Linux 下篇帖子: 基于docker创建ansible以及管理容器节点
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表