Ansible roles

Ansible roles

roles不管是Ansible还是saltstack,我在写一键部署的时候,都不可能把所有的步骤全部写入到一个'剧本'文件当中,我们肯定需要把不同的工作模块,拆分开来,解耦,那么说到解耦,我们就需要用到roles官方推荐,因为roles的目录结构层次更加清晰。
例如:我们之前推荐大家写一个base.yml里面写所有基础优化的项目,其实把所有东西摞进去也是很鸡肋的,不如我们把这些功能全部拆分开,谁需要使用,就调用即可。

建议:每个roles最好只使用一个tasks这样方便我们去调用,能够很好的做到解耦。(SOA)

Ansible roles目录结构

官方推荐最佳实战目录结构定义方式

production                # inventory file for production servers
staging                   # inventory file for staging environment

group_vars/
   group1.yml             # here we assign variables to particular groups
   group2.yml
host_vars/
   hostname1.yml          # here we assign variables to particular systems
   hostname2.yml

library/                  # if any custom modules, put them here (optional)
module_utils/             # if any custom module_utils to support modules, put them here (optional)
filter_plugins/           # if any custom filter plugins, put them here (optional)

site.yml                  # master playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

roles目录结构使用galaxy创建

[root@m01 ~]# cd /etc/ansible/roles/

[root@m01 roles]# tree wordpress/
nfs/                #项目名称
├── defaults        #低优先级变量
├── files           #存放文件
├── handlers        #触发器文件
├── meta            #依赖关系文件
├── tasks           #工作任务文件
├── templates       #jinja2模板文件
├── tests           #测试文件
└── vars            #变量文件

Ansible roles依赖关系

roles允许你在使用roles时自动引入其他的roles。role依赖关系存储在role目录中meta/main.yml文件中。

例如:推送wordpress并解压,前提条件,必须要安装nginx和php,把服务跑起来,才能运行wordpress的页面,此时我们就可以在wordpress的roles中定义依赖nginx和php的roles

[root@m01 roles]# vim /etc/ansible/roles/wordpress/meta/main.yml
dependencies:
  - { role: nginx }
  - { role: php }
[root@m01 meta]# vim main.yml 
dependencies:
  - { role: rsync_server }

如果编写了meta目录下的main.yml文件,那么Ansible会自动先执行meta目录中main.yml文件中的dependencies文件,如上所示,就会先执行nginx和php的安装。

Ansible Roles最佳实战


roles小技巧

1.创建roles目录结构,手动使用ansible-galaxy init test role

2.编写roles功能

3.在playbook中引用


使用roles重构rsync

1)规划目录结构

[root@m01 rsync]# cd /etc/ansible/roles/
[root@m01 roles]# ll
总用量 0
[root@m01 roles]# ansible-galaxy init rsync roles
- rsync was created successfully
[root@m01 roles]# tree
.
└── rsync
    ├── defaults
    │   └── main.yml
    ├── files
    ├── handlers
    │   └── main.yml
    ├── meta
    │   └── main.yml
    ├── README.md
    ├── tasks
    │   └── main.yml
    ├── templates
    ├── tests
    │   ├── inventory
    │   └── test.yml
    └── vars
        └── main.yml

2)定义roles主机清单

[root@m01 roles]# cat /etc/ansible/roles/hosts 
[backup]
172.16.1.41

3)指定backup主机组,执行那个roles

[root@m01 roles]# cat /etc/ansible/roles/site.yml 
- hosts: backup
  remote_user: root
  roles:
    - rsync

4)查看rsync角色的tasks任务

[root@m01 roles]# cat /etc/ansible/roles/rsync/tasks/main.yml 
- name: Install Rsync Server
  yum: name=rsync state=present

- name: Configure Rsync Server
  copy:
    src: "{{ item.src }}"
    dest: /etc/"{{ item.dest }}"
    mode: "{{ item.mode }}"
  with_items:
    - {src: "rsyncd.conf", dest: "rsyncd.conf", mode: "0644"}
    - {src: "rsync.passwd", dest: "rsync.passwd", mode: "0600"}
  notify: Restart Rsync Server

- name: Start Rsync Server
  systemd:
    name: rsyncd
    state: started
    enabled: yes

5)查看rsync角色的handlers

[root@m01 roles]# cat /etc/ansible/roles/rsync/handlers/main.yml 
- name: Restart Rsync Server
  service:
    name: rsyncd
    state: restarted

6)查看rsync角色的files目录

[root@m01 roles]#  ll /etc/ansible/roles/rsync/files/
total 8
-rw-r--r-- 1 root root 322 Nov 16 18:49 rsyncd.conf
-rw------- 1 root root  20 Nov 16 18:30 rsync.passwd

7)执行roles,使用-t指定执行测试rsync角色

[root@m01 roles]# ansible-playbook -i hosts  -t rsync site.yml 
PLAY [backup] ********************************************************************************************

TASK [Gathering Facts] ********************************************************************************
ok: [172.16.1.41]

TASK [backup : Install Rsync Server] ***********************************************************************
ok: [172.16.1.41]

TASK [backup : Configure Rsync Server] *********************************************************************
ok: [172.16.1.41]

TASK [backup : Start Rsync Server] *************************************************************************
ok: [172.16.1.41]

PLAY RECAP ********************************************************************************************
172.16.1.41                : ok=5    changed=0    unreachable=0    failed=0  

使用roles重构nfs

1)使用roles创建nfs服务,目录结构如下

[root@m01 roles]# tree /etc/ansible/roles

├── group_vars
│   └── all
├── hosts
├── nfs
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   │   └── exports
│   └── vars
├── site.yml

2)定义roles主机清单

[root@m01 roles]# cat /etc/ansible/roles/hosts 
[nfs]
172.16.1.31

3)指定nfs主机组,执行那个roles

[root@m01 roles]# cat /etc/ansible/roles/site.yml 
- hosts: nfs
  remote_user: root
  roles:
    - nfs
  tags: nfs

4)查看nfs角色的tasks任务

[root@m01 roles]# cat /etc/ansible/roles/nfs/tasks/main.yml 
- name: Install Nfs-Server
  yum:
    name:nfs-utils
    state: present

- name: Configure Nfs-Server
  template:
    src: exports
    dest: /etc/exports
  notify: Restart Nfs-Server

- name: Create Directory Data
  file:
    path: "{{ share_dir }}"
    state: directory
    owner: www
    group: www
    mode: 0755

- name: Start Nfs-Server
  systemd:
    name: nfs
    state: started
    enabled: yes

5)查看nfs角色的handlers

[root@m01 roles]# cat /etc/ansible/roles/nfs/handlers/main.yml 
- name: Restart Nfs-Server
  systemd:
    name: nfs
    state: restarted

6)查看rsync 角色的files目录

[root@m01 roles]# cat /etc/ansible/roles/nfs/templates/exports 
{{ share_dir }} {{ share_ip }}(rw,sync,all_squash,anonuid=666,anongid=666)

7)nfs对应的变量定义

[root@m01 roles]# cat /etc/ansible/roles/group_vars/all 
#nfs
share_dir: /data
share_ip: 172.16.1.31

8)执行roles,使用-t指定执行nfs标签

[root@m01 roles]# ansible-playbook -i hosts  -t nfs site.yml 
PLAY [nfs] ********************************************************************************************

TASK [Gathering Facts] ********************************************************************************
ok: [172.16.1.31]

TASK [nfs : Install Nfs-Server] ***********************************************************************
ok: [172.16.1.31]

TASK [nfs : Configure Nfs-Server] *********************************************************************
ok: [172.16.1.31]

TASK [nfs : Create Directory Data] ********************************************************************
ok: [172.16.1.31]

TASK [nfs : Start Nfs-Server] *************************************************************************
ok: [172.16.1.31]

PLAY RECAP ********************************************************************************************
172.16.1.31                : ok=5    changed=0    unreachable=0    failed=0   

Ansible Galaxy

Galaxy是一个免费网站,类似于github网站,网站上基本都是共享roles,从Galaxy下载roles是最快启动项目方式之一。

Galaxy官方网站:https://galaxy.ansible.com/

ansible提供了一个命令ansible-galaxy,可以用来对roles项目进行初始化,查找,安装,移除等操作

[root@m01 roles]# ansible-galaxy --help
Usage: ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...

Perform various Role related operations.

Options:
  -h, --help            show this help message and exit
  -c, --ignore-certs    Ignore SSL certificate validation errors.
  -s API_SERVER, --server=API_SERVER
                        The API server destination
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit

 See 'ansible-galaxy <command> --help' for more information on a specific
command.

使用galaxy搜索项目

[root@m01 roles]# ansible-galaxy search openvpn

Found 103 roles matching your search:

 Name                                      Description
 ----                                      -----------
 AdrienKuhn.fail2ban                       Configure fail2ban jails
 AdrienKuhn.ufw                            Configure firewall with UFW
 alexiscangelosi.openvpn                   Ansible role openvpn
 andrelohmann.easy_rsa                     ansible galaxy role to deploy easy-rsa
 andrelohmann.openvpn                      ansible galaxy role to deploy an openvpn server
 antoniobarbaro.openvpn-client             Install openvpn client, configure and start service
 arillso.openvpn                           Configurate your OpenVPN Client
 asm0dey.ansible_role_openvpn              OpenVPN playbook for CentOS/Fedora/RHEL/RHEL clones & Ubuntu/Debian
 barbudone.pritunl_server                  Pritunl for EL Linux.
 blaet.openvpn                             OpenVPN playbook for CentOS/Fedora/RHEL/RHEL clones & Ubuntu/Debian
 bmcclure.pia                              Manages Private Internet Access VPN utilizing the AUR and openvpn on Archlinux
 borkenpipe.ansible_openvpn                OpenVPN with PKI for Ubuntu/Debian
 borkenpipe.openvpn                        Install OpenVPN for us with AWS bastions.
 borkenpipe.stouts_openvpn                 Manage OpenVPN server
 cinject.openvpn                           Openvpn role
 clvx.easy-rsa                             Role to generate an openvpn pki.
 clvx.openvpn                              Role to deploy server and openvpn clients.
 cornfeedhobo.openvpn                      Install and manage OpenVPN
 d3atiq.openvpn_client                     A role for automatic managed connection to OpenVPN VPN.
 danrabinowitz.openvpn_for_access          This role provisions an OpenVPN server. This server is NOT designed for routing all traffic from the client. It is for granting access to the server, so that ssh (for example) can be allowed ONLY
 dresden-weekly.openvpn                    collection of Ansible roles to run OpenVPN.
 edeckers.openvpn-ldap                     Installs an OpenLDAP backed OpenVPN-server
 egeneralov.openvpn                        Provision openvpn servers
 ehime.openvpn                             OpenVPN playbook for CentOS/Fedora/RHEL/RHEL clones & Ubuntu/Debian
 escapace.ansible_openvpn                  openvpn role
 gavika.easy_rsa                           Install and configure EasyRSA
 gavika.openvpn                            Role to install and configure OpenVPN server and generate client configurations
 gregorydulin.ansible_role_openvpn         OpenVPN playbook for CentOS/Fedora/RHEL/RHEL clones & Ubuntu/Debian
 grycap.openvpn                            Install OpenVPN to create hybrid clusters with EC3
 iamsudipt.openvpn                         OpenVpn ansible role for creating a secure tunnel to your private infra.
 icasimpan.ansible_role_openvpn            OpenVPN playbook for CentOS/Fedora/RHEL/RHEL clones & Ubuntu/Debian
 ieguiguren.nordvpn                        downloads NordVPN servers' list and set it up
 indigo-dc.openvpn                         Install OpenVPN to create hybrid clusters with EC3
 indix.openvpn-ops                         This repo can be used to create a openvpn server.
 iroquoisorg.openvpn                       manage openvpn server
 iroquoisorg.openvpn_client                install openvpn client
 jtyr.openvpn                              Role which helps to install and configure OpenVPN server.
 juju4.openvpnclient                       setup openvpn as client
 kbrebanov.openvpn                         Installs and configures OpenVPN
 kbrebanov.openvpn_as                      Installs and configures OpenVPN Access Server
 kharkevich.pritunl                        Deploy pritunl: Enterprise Distributed OpenVPN and IPsec Server.
 kostyrevaa.openvpn                        Installs and configures openvpn client
 kyl191.openvpn                            OpenVPN playbook for CentOS/Fedora/RHEL/RHEL clones & Ubuntu/Debian
 leafnode.openvpn_client                   install openvpn client
 linuxhq.iproute                           RHEL/CentOS - Advanced IP routing and network device configuration tools
 linuxhq.openvpn_client                    RHEL/CentOS - The Open Source VPN (client)

查看详细信息

[root@m01 roles]# ansible-galaxy info kostyrevaa.openvpn

Role: kostyrevaa.openvpn
        description: Installs and configures openvpn client
        active: True
        commit:
        commit_message:
        commit_url:
        company:
        created: 2015-08-17T18:13:15.551754Z
        download_count: 20
        forks_count: 0
        github_branch: master
        github_repo: ansible-openvpn
        github_user: kostyrev
        id: 4798
        imported: None
        is_valid: True
        issue_tracker_url: https://github.com/kostyrevaa/ansible-openvpn/issues
        license: license (GPLv3)
        min_ansible_version: 1.2
        modified: 2018-04-13T06:31:20.195475Z
        open_issues_count: 0
        path: (u'/root/.ansible/roles', u'/usr/share/ansible/roles', u'/etc/ansible/roles')
        role_type: ANS
        stargazers_count: 0
        travis_status_url:

安装项目

[root@m01 roles]# ansible-galaxy install kyl191.openvpn
- downloading role 'openvpn', owned by kyl191

原文地址:https://www.cnblogs.com/gongjingyun123--/p/11600348.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


----name:setpublickeyonremotehosts&setreomtehostssudoersfilehosts:all#此脚本要求所有的主机root用户密码相同become:noremote_user:rootvars:-remoteuser:user1:rhcetasks:-name:setsecondarygroupforrhce
环境准备#cat/etcedhat-releaseCentOSLinuxrelease7.9.2009(Core)#pythonPython3.7.11(default,Jul312022,16:12:35)[GCC4.8.520150623(RedHat4.8.5-44)]onlinuxType"help","copyright","credits"or"li
准备好环境,在安装之前请先了解openshift提供的ansible有大量的安装选项文档地址:https://docs.okd.io/latest/install/configuring_inventory_file.html1、配置/etc/ansible/hosts 
Ansible:运维工作:系统安装(物理机、虚拟机)-->程序包安装、配置、服务启动-->批量操作-->程序发布-->监控OSProvisioning:物理机:PXE、Cobbler虚拟机:ImageTemplatesConfigration:puppet(ruby)saltstack(python)chefcfengineCommandand
ansible与salt对比相同都是为了同时在多台机器上执行相同的命令都是python开发不同agent(saltstack需要安装、ansible不需要)配置(salt配置麻烦,ansible基本不用配置)学习路线(salt比较陡峭,ansible比较平缓)第三方工具(salt比较少)开源社区的对接(salt比较少)现有用户(salt还是an
[root@node1playbook]#catnginx.yml-hosts:test\\主机组,要和nginx.yml在同一个目录下remote_user:root\\远端执行任务的用户tasks:\\任务-name:installhttpd\\任务描述command:yum-yinstallhttpd\\调用ansible的command模块安装httpd-na
一直不知道这个模块到底在哪,并且也挺想搞清楚官方那些模块到底在哪个目录下。1.使用grep-rl"copy.py"/usr/lib/python2.7/site-packages/ansible(这个目录是专门放ansible源码目录的)然后找到是/usr/lib/python2.7/site-packages/ansible/modules/files/copy.py这个文件,这里需要
ansile作为去除安装agent的自动化工具,通过ssh协议的简单功能强大的自动化工作。在ansile使用的过程中,有三种用途1、ansible自行一次性任务,即执行命令如:ansible10.59.87.11-mping*ansible"dev-hdp"-mcopy-a"src=oot/HfHadoopHiveUdf.jardest=/data1/opt/cloudera/par
ansible-playbook(1) Ansible组成部分InventoryModulesAdHocCommandsplaybooksplaybooks:Tasks:任务,即调用的模块完成的某操作variables:变量Templates:模版Roles:角色 基本结构:-host:webserverremote_user:tasks:
报错:[root@jenkins~]#ansiblego_activity-mcron-a"name='log_clear'minute=0hour=2job=find/home/golanger/log/-typef-name'log$(date+\%d-d-1day)'-delete"ERROR!thistask'cron'hasextraparams,wh
一、测试环境说明1、系统:rhel6.92、ip地址:20.20.20.24/2420.20.20.41/2420.20.20.42/243、以下操作使用root身份进行,也可以使用具有sudo权限的用户进行相关操作二、环境准备1、关闭iptables防火墙、selinux#/etc/init.d/iptablesstop#
ansible常用模块安装:依赖于epel源yuminstallansible-y配置文件:/etc/ansible/ansible.cfgInvertoory:/etc/ansible/hosts 如何查看模块帮助:ansible-doc-lansible-doc-sMODULE_NAME` ansible命令应用基础:语法:ansible<host-pattern>[options]-fforks
copycopy模块是将ansible管理主机上的文件拷贝上远程主机中,与fetch相反,如果目标路径不存在,则自动创建,如果src的目录带“/”则复制该目录下的所有东西,如果src的目录不带“/”则连同该目录一起复制到目标路径;常用模块src参数:用于指定需要copy的文件或目录
9.YAML9.1简介(1)YAML是一个可读性高的用来表达资料序列的格式。(2)YAML参考了其它多种语言。包括:XML、C语言、python、perl以及电子邮件格式的RFC2822等。ClarkEvans在2001年首次发表了这种语言。(3)YAML不是XML,在开发这种语言时,YAML的意思其实是:yetanothermarkuplanguage,9.2特性(1)YA
了解ansibleansible批量在远程主机上执行命令ansible主要是为了进行操作多个主机而进行的#!/bin/envpython文件中直接指向python文件#!/bin/base 指行脚本一.ansible第一步.下载epel源wget-O/etc/yum.repos.d/epel.repohttp://mirrors.aliyun.comepo/epel-7.repo
背景:在私有云环境下,遇到要开通某个项目,则需要快速的响应创建虚拟机,并且做一些基础的配置。为了提高效率以及减少手工犯错的概率,一般会采取ansible批量部署,但是使用ansible的前提是预先配置好免密。在密码一致的场景中,可以使用expect优化做免密的过程解决方案:1.
简单例子1:vars定义变量-hosts:allremote_user:rootvars:-package:nginx-service:nginx tasks:-name:installnginxpackage yum:name={{package}}state=latest-name:installconfigurationfileforhttpd copy:src=/etcginxginx
 ansible自动化运维工具的介绍      ansible结构特性:            模块化,调用特定的模块,完成特定的任务;        基于Python语言实现,由Paramiko、PyYAML和Jinja2三个关键模块;        部署简单,agentless        主从模
---恢复内容开始---Templates:模版 cat/etc/ansible/hosts  cattemplatesginx.conf.j2 -hosts:testremote_user:rootvars:-package:httpd-service:httpdtasks:-name:installnginxpackage yum:name={{package}}state=la
1、配置资源清单inventory文件[root@test1~]#cat>/etc/ansible/hosts<<EOF[k8s]192.168.0.92ansible_ssh_port=22ansible_ssh_user=k8sansible_ssh_pass='123'ansible_become_pass='123456'EOF解释:ansible_ssh_pass='123'