0
点赞
收藏
分享

微信扫一扫

ansible学习笔记08

1、 ansible role

在生产环境中,有大量的工作是重复的,同样的,playbook也会大量重复使用,如何更高效的使用playbook,这个时候role就能发挥他的作用了,role能以一种更简单的方式重用playbook。

举一个例子,配置mysql的时候,总会有大量而且重复的操作,如果编写一个role,在每次配置的时候只需要修改其中的个别变量就能实现配置的差异化,而且能节省很多时间。

1.1 ansible role的优点

  1. 简化工作量,提高工作效率
  2. 重复playbook
  3. 管理大型项目更加方便
  4. 在不同环境定制不同role
  5. 很多人一起开发,提高效率

1.2 ansible role标准目录结构

[student@workstation file-review]$ tree test/
test/
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml
目录 说明
defaults 优先级很低的变量(缺省值)
files 需要用到的文件
handlers notify声明执行
meta 使用说明,作者等信息
tasks 存放play
templates 需要用到的模板(.j2)
tests 存放测试用例
vars 优先级高的变量

1.3 在playbook中使用role

# 使用roles下面列出role
---
- hosts: remote.example.com
  roles:
    - role1
    - role2

1.4 在role下定义变量

# 在vars目录下定义变量,使用key:value方式定义变量
host: home
name: xiaoming
# 在playbook下定义变量
---
- hosts: xiaoming
  roles:
    - role: role1
    - role: role2
      var1: hello
      var2: world

1.5 tasks的优先级

生产环境下尽量避免出现多个tasks,以免造成混淆

名称 优先级从高到低
pre_task 最高
role_task(在role中定义)
play_tasks
post_task

2、 rhel-system-roles

在RHEL7.4,红帽推出了rhel-system-roles,方便更快捷的管理主机

名称 说明
rhel-system-roles.kdump 管理系统崩溃
rhel-system-roles.network 管理网络
rhel-system-roles.selinux 管理selinux
rhel-system-roles.timesync 管理时间同步
rhel-system-roles.postfix 管理邮件服务器
rhel-system-roles.firewall 管理防火墙
rhel-system-roles.tuned 系统调优

2.1 安装rhel-system-roles

命令: yum install rhel-system-roles

# 通过安装rhel-system-roles,使用系统roles
[student@workstation ~]$ sudo yum install rhel-system-roles
[sudo] password for student:
Last metadata expiration check: 0:35:02 ago on Sun 21 Aug 2022 11:29:45 PM CST.
Dependencies resolved.
======================================================================================================================================================================================================
 Package                                         Arch                                 Version                                  Repository                                                        Size
======================================================================================================================================================================================================
Installing:
 rhel-system-roles                               noarch                               1.0-5.el8                                rhel-8.0-for-x86_64-appstream-rpms                               127 k

Transaction Summary
======================================================================================================================================================================================================
Install  1 Package

Total download size: 127 k
Installed size: 827 k
Is this ok [y/N]: y
Downloading Packages:
rhel-system-roles-1.0-5.el8.noarch.rpm                                                                                                                                1.3 MB/s | 127 kB     00:00
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                 1.3 MB/s | 127 kB     00:00
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                                                              1/1
  Installing       : rhel-system-roles-1.0-5.el8.noarch                                                                                                                                           1/1
  Verifying        : rhel-system-roles-1.0-5.el8.noarch                                                                                                                                           1/1

Installed:
  rhel-system-roles-1.0-5.el8.noarch

Complete!
[student@workstation ~]$ ls -l /usr/share/ansible/roles
total 0
lrwxrwxrwx.  1 root root  23 Jan 14  2019 linux-system-roles.kdump -> rhel-system-roles.kdump
lrwxrwxrwx.  1 root root  25 Jan 14  2019 linux-system-roles.network -> rhel-system-roles.network
lrwxrwxrwx.  1 root root  25 Jan 14  2019 linux-system-roles.postfix -> rhel-system-roles.postfix
lrwxrwxrwx.  1 root root  25 Jan 14  2019 linux-system-roles.selinux -> rhel-system-roles.selinux
lrwxrwxrwx.  1 root root  26 Jan 14  2019 linux-system-roles.timesync -> rhel-system-roles.timesync
drwxr-xr-x.  9 root root 173 Aug 22 00:04 rhel-system-roles.kdump
drwxr-xr-x.  8 root root 196 Aug 22 00:04 rhel-system-roles.network
drwxr-xr-x.  6 root root 114 Aug 22 00:04 rhel-system-roles.postfix
drwxr-xr-x.  7 root root 139 Aug 22 00:04 rhel-system-roles.selinux
drwxr-xr-x. 10 root root 188 Aug 22 00:04 rhel-system-roles.timesync

2.2 查看markdown说明

每一个rhel-system-roles,都有README.md说明

[student@workstation ~]$ tail -n 10  /usr/share/ansible/roles/rhel-system-roles.selinux/README.md
    selinux_logins:
      - { login: 'plautrba', seuser: 'staff_u', state: 'absent' }
      - { login: '__default__', seuser: 'staff_u', serange: 's0-s0:c0.c1023', state: 'present' }
```

## Ansible Facts

### selinux\_reboot\_required

This custom fact is set to `true` if system reboot is necessary when SELinux is set from `disabled` to `enabled` or vice versa.  Otherwise the fact is set to `false`.  In the case that system reboot is needed, it will be indicated by returning failure from the role which needs to be handled using a `block:`...`rescue:` construct. The reboot needs to be performed in the playbook, the role itself never reboots the managed host. After the reboot the role needs to be reapplied to finish the changes.
...

2.3 使用timesync

# 查看示例用法
- hosts: targets
  vars:
    timesync_ntp_servers:
      - hostname: foo.example.com
        iburst: yes
      - hostname: bar.example.com
        iburst: yes
      - hostname: baz.example.com
        iburst: yes
  roles:
    - rhel-system-roles.timesync

# 相关变量
# List of NTP servers
timesync_ntp_servers:
  - hostname: foo.example.com   # Hostname or address of the server
    minpoll: 4                  # Minimum polling interval (default 6)
    maxpoll: 8                  # Maximum polling interval (default 10)
    iburst: yes                 # Flag enabling fast initial synchronization
                                # (default no)
    pool: no                    # Flag indicating that each resolved address
                                # of the hostname is a separate NTP server
                                # (default no)

# List of PTP domains
timesync_ptp_domains:
  - number: 0                   # PTP domain number
    interfaces: [ eth0 ]        # List of interfaces in the domain
    delay: 0.000010             # Assumed maximum network delay to the
                                # grandmaster in seconds
                                # (default 100 microsecond)
    transport: UDPv4            # Network transport: UDPv4, UDPv6, L2
                                # (default UDPv4)
    udp_ttl: 1                  # TTL for UDPv4 and UDPv6 transports
                                # (default 1)

# Flag enabling use of NTP servers provided by DHCP (default no)
timesync_dhcp_ntp_servers: no

# Minimum offset of the clock which can be corrected by stepping (default is
# specific to NTP/PTP implementation: chrony 1.0, ntp 0.128, linuxptp 0.00002).
# Zero threshold disables all steps.
timesync_step_threshold: 1.0

# Minimum number of selectable time sources required to allow synchronization
# of the clock (default 1)
timesync_min_sources: 1

# Name of the package which should be installed and configured for NTP.
# Possible values are "chrony" and "ntp". If not defined, the currently active
# or enabled service will be configured. If no service is active or enabled, a
# package specific to the system and its version will be selected.
timesync_ntp_provider: chrony
# 使用timesync
[student@workstation file-review]$ cat timesync.yml
---
- hosts: targets
  vars:
    timesync_ntp_servers:
      - hostname: 0.rhel.pool.ntp.org
        iburst: yes
      - hostname: 1.rhel.pool.ntp.org
        iburst: yes
      - hostname: 2.rhel.pool.ntp.org
        iburst: yes
      - hostname: 3.rhel.pool.ntp.org
        iburst: yes
    timezone: UTC
  roles:
    - rhel-system-roles.timesync
  tasks:
          - name: set timezone
            timezone:
                    name: "{{ timezone }}"

2.4 自定义roles

  1. 配置文件指定:~/.ansible/roles:/usr/share/ansible/roles:自定义roles路径

  2. ansible-galax init role名称

  3. 定义tasks

  4. 在playbook中导入roles
# 修改配置文件
[student@workstation file-review]$ cat ansible.cfg
[defaults]
inventory = inventory
ansible_managed = Ansible managed: modified on %Y-%m-%d %H:%M:%S
roles_path = /usr/share/ansible/roles:./roles
[student@workstation file-review]$ ansible-galaxy list
# /usr/share/ansible/roles
- linux-system-roles.kdump, (unknown version)
- linux-system-roles.network, (unknown version)
- linux-system-roles.postfix, (unknown version)
- linux-system-roles.selinux, (unknown version)
- linux-system-roles.timesync, (unknown version)
- rhel-system-roles.kdump, (unknown version)
- rhel-system-roles.network, (unknown version)
- rhel-system-roles.postfix, (unknown version)
- rhel-system-roles.selinux, (unknown version)
- rhel-system-roles.timesync, (unknown version)
# /home/student/file-review/roles
- mmx, (unknown version)
[student@workstation file-review]$ ansible-galaxy init mmx
- mmx was created successfully
[student@workstation file-review]$ tree mmx
mmx
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml

8 directories, 8 files
# 定义roles执行的vars
[student@workstation file-review]$ cat roles/mmx/vars/main.yml
---
# vars file for mmx
name: mmx
age: 22
like: play

# 定义roles执行的tasks
[student@workstation file-review]$ cat roles/mmx/tasks/main.yml
---
# tasks file for mmx
- debug:
        msg: "name={{ name }} age={{ age }} like={{ like }}"

# 使用自定义roles
[student@workstation file-review]$ cat role_playbook.yml
---
- name: use role
  hosts: all
  tasks:
  roles:
    - role: mmx
[student@workstation file-review]$ ansible-playbook role_playbook.yml
 [WARNING]: Found variable using reserved name: name

PLAY [use role] **************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************************************************************************
ok: [serverb.lab.example.com]

TASK [mmx : debug] ***********************************************************************************************************************************************************************************************************
ok: [serverb.lab.example.com] => {
    "msg": "name=mmx age=22 like=play"
}

PLAY RECAP *******************************************************************************************************************************************************************************************************************
serverb.lab.example.com    : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

3、 ansible galax

访问网站:https://galaxy.ansible.com,该网站有大量写好的roles可以使用,总之一句话,一定要看得懂别人写的是啥,不然有现成的你也不会用...

3.1 网页浏览ansible galax

image20220822004745671.png

可以通过搜索,搜索相关的role

image20220822005120830.png

搜索一个自动化安装openstack的role

image20220822005701711.png

3.2 命令搜索

ansible-galax search 关键字

参数 说明
--platforms 平台
--author 作者
--galaxy-tags 标签
[root@mmx_ansible ~]# ansible-galaxy search cisco

Found 68 roles matching your search:

 Name                                             Description
 ----                                             -----------
 ansible-network.cisco_ios                        This role provides an implementation for automating the configuration of
Cisco IOS/IOS-XE devices.  It provides implementations of Ansible Network
configuration abstractions.
 ansible-network.cisco_iosxr                      Ansible role for managing Cisco IOS-XR devices
 ansible-network.cisco_nxos                       Ansible role for managing Cisco NX-OS devices
 ansible-network.cloud_vpn                        This role provides functions to manage IPSEC VPN tunnels.
 ansible_security.acl_manager                     Ansible role to manage access control lists for many firewall devices
 avinetworks.avicontroller_csp                    Deploy's the AVI Vantage Controller on Cisco CSP
 avinetworks.network_interface                    This roles enables users to configure various network components on target machines.
 bsmeding.ansible_role_nautobot                   Installs Nautobot (fork from Netbox) CMDB
 chouseknecht.ios                                 Ansible role for managing Cisco IOS/IOS-XE devices
 christopherjhart.trex                            Install the Cisco TRex traffic generator
 CiscoUcs.ucs                                     Cisco UCS Developer
 clay584.parse_genie                              Filter plugin for network CLI parsing using Cisco's Genie/pyATS
 CoffeeITWorks.ansible_nagios4_server_snmptrap    Install and setup snmp traps services and dependencies
 colin_mccarthy.servicenow_network_tickets        your description
 datacenter.aci-model                             Comprehensive Ansible role to model and deploy Cisco ACI fabrics
 ericovis.cloud-center                            Ansible role for installing the Cisco's Cloud Center CCM
 eugene_ky_wong.viptela_ansible                   This is the Cisco Viptela Ansible SDK
 faridjoubbi.ansible_role_cisco_asa_backup_config Creates backups of Cisco ASA configurations, both with and without security contexts.
 foo2k.network_interface                          This roles enables users to configure various network components on target machines.
 Im0.cisco-openVuln                               Queries the Cisco Product Security Incident Response Team (PSIRT) openVuln API
 Im0.cisco_upgrader                               Upgrade a number of different Cisco network devices operating systems
 ios-xr.iosxr-ansible                             IOS-XR device automation tool
 jiholland.bmc_asset                              Create asset in BMC Remedy based on gathered facts from Cisco Catalyst and Nexus devices.
 jiholland.network_backup                         Backup the running-configuration from network-devices to git-repository.
 jiholland.network_upgrade                        Upgrade OS (or check/upload/schedule) to compliant version on Cisco Catalyst and Nexus devices.
 jklaiber.asa_backup                              Ansible Role for making a full Cisco ASA backup
 kecorbin.vpn-router                              Ansible Role to terminate IPSec tunnel on Cisco IOS router
 kenjones_cisco.ansible_role_logstash             Ansible role for Logstash
 kovarus.networkbackup                            Network Backups
 kurrier.cisco_backup                             Adds the ability for Ansible to backup Cisco Devices
 linux-system-roles.vpn                           Configure VPN
 lucasmaurice.network_interface                   Ansible Role for managing Network Interfaces
 lukedrussell.cisco_ios                           This role provides an implementation for automating the configuration of
Cisco IOS/IOS-XE devices.  It provides implementations of Ansible Network
configuration abstractions.
 maxrainer.cisco_iosupgrade                       Ansible Role for Cisco IOS device image upgrade
 maxrainer.cisco_ise                              maintain Cisco Identity Services Engine
 maxrainer.ios_router                             Cisco IOS Router role for Demo and Labs
 maxrainer.network_aci                            Cisco ACI Role for Demo and Labs
 maxrainer.network_update                         Role for Demo and Labs on network device updates
 maxrainer.routing_bgp                            manipulation of BGP config on different platforms in different ways
 mixja.csr1000v                                   Deploys Cisco CSR 1000V virtual router to VMWare Fusion on OS X
 mixja.vwlc                                       Deploys the Cisco Virtual Wireless Controller to VMWare Fusion on OS X
 mjuenema.filter-cisco-hash                       Jinja2 Cisco password hash filters
 mohdya.cisco_general_iosxe                       your description
 mrlesmithjr.elk-processors                       An Ansible role to provision ELK Stack processors..
 mrlesmithjr.rancid-git                           Installs rancid (Really Awesome New Cisco confIg Differ) - Configurable (Git enabled)
 nkakouros.ansible_role_honeyd                    Ansible role to install HoneyD
 oliverl_21.cisco_api                             Cisco API role
 oliverl_21.cisco_ios_update                      Cisco IOS Update role
 oliverl_21.ios_config                            Cisco IOS Configuration role
 o_sole_meo.network_interface                     Ansible Role for managing Network Interfaces
 ovirt.infra                                      Role to manage oVirt infrastructure.
 polo445432.cisco_test                            your role description
 rogerscuall.evpn_vxlan-leaf                      Cisco EVPN/VXLAN
 rogerscuall.evpn_vxlan-spine                     Cisco EVPN/VXLAN
 runsi.ansible_viptela                            your description
 securenetwrk.gold_config                         Ansible Role to check and enforce a "golden config"
 securenetwrk.ios_vrf                             Ansible Role to deploy a set of VRFs to Cisco IOS network gear
 securenetwrk.network_vrf                         Ansible Role to deploy a set of VRFs to Cisco network gear
 sfromm.librenms                                  Role to manage librenms
 Smartbrood.cpar-ansible-role                     Backup Cisco Prime Access Registrar
 ssato.nw_backup_config                           Backup running configurations on network nodes
 ssunlau.huawei_sw_interfaces_telnet              gather facts - interfaces (Telnet) from Huawei Switches for Ansible
 stevenca.ansible_nfvis                           your description
 swaqqii.ios_create_user                          Ansible role to create users on cisco-ios
 termlen0.ios_check_acls                          Ansible role for checking if source/destination tuple matches Cisco IOS extended ACLS
 vinayski.ansible-role-vpnc-client                VPN client for Cisco VPN3000 Concentrator, IOS and PIX
 vinealvees.backup_sw_config                      With this role you can perform backup of the configurations of your Cisco equipments with IOS.
 vinealvees.general_configs                       This role setting some basics configures at Cisco Switch like Banner, SSH, Password Encryption, Time, Domain and HTTP Server.

3.3 下载一个roles

[root@mmx_ansible ~]# cd /root/.ansible/roles/ansible-network.cloud_vpn
[root@mmx_ansible ansible-network.cloud_vpn]# ls
bindep.txt  CHANGELOG.rst  changelogs  defaults  docs  LICENSE  meta  README.md  requirements.txt  tasks  test-requirements.txt  tests  tox.ini

[root@mmx_ansible ~]# ansible-galaxy install ansible-network.cloud_vpn
Starting galaxy role install process
- downloading role 'cloud_vpn', owned by ansible-network
- downloading role from https://github.com/ansible-network/cloud_vpn/archive/v2.7.1.tar.gz
- extracting ansible-network.cloud_vpn to /root/.ansible/roles/ansible-network.cloud_vpn
- ansible-network.cloud_vpn (v2.7.1) was installed successfully

[root@mmx_ansible ansible-network.cloud_vpn]# tree .
.
├── bindep.txt
├── CHANGELOG.rst
├── changelogs
│   ├── config.yaml
│   └── fragments
│       ├── v0-initial-release.yaml
│       ├── v261-fix-meta-suffix.yaml
│       ├── v262-decouple-providers-provisioners.yaml
│       ├── v270-initial-release.yaml
│       └── v271-release.yaml
├── defaults
│   └── main.yaml
├── docs
│   ├── aws_providers_arguments.md
│   ├── azure_providers_arguments.md
│   ├── cloud_providers_arguments.md
│   ├── common_arguments.md
│   ├── create_vpn.md
│   ├── delete_vpn.md
│   ├── network_appliance_providers_arguments.md
│   └── openstack_providers_arguments.md
├── LICENSE
├── meta
│   └── main.yml
├── README.md
├── requirements.txt
├── tasks
│   ├── add_host_initiator.yaml
│   ├── add_host_responder.yaml
│   ├── configure_routing_initiator.yaml
│   ├── configure_routing_responder.yaml
│   ├── configure_vpn_initiator.yaml
│   ├── configure_vpn_responder.yaml
│   ├── create_vpn.yaml
│   ├── delete_vpn.yaml
│   ├── deprovision_initiator.yaml
│   ├── deprovision_responder.yaml
│   ├── get_provisioner_facts_initiator.yaml
│   ├── get_provisioner_facts_responder.yaml
│   ├── get_vpn_facts.yaml
│   ├── install_pip_requirements.yaml
│   ├── load_initiator_defaults.yaml
│   ├── load_responder_defaults.yaml
│   ├── loop_tunnels.yaml
│   ├── main.yaml
│   ├── post_configure_initiator_hooks.yaml
│   ├── post_configure_responder_hooks.yaml
│   ├── process_tunnel.yaml
│   ├── provision_initiator.yaml
│   ├── provision_responder.yaml
│   ├── show_login_info_initiator.yaml
│   ├── show_login_info_responder.yaml
│   ├── unconfigure_initiator.yaml
│   └── unconfigure_responder.yaml
├── test-requirements.txt
├── tests
│   ├── ansible.cfg
│   ├── run_tests.sh
│   ├── secrets.yaml.sample
│   ├── test_aws_csr_to_aws_vpn_bgp.yaml
│   ├── test_aws_csr_to_aws_vpn.yaml
│   ├── test_aws_csr_to_aws_vyos.yaml
│   ├── test_aws_to_aws.yaml
│   ├── test_aws_vyos_to_aws_vpn.yaml
│   ├── test_aws_vyos_to_aws_vyos_bgp.yaml
│   ├── test_aws_vyos_to_aws_vyos.yaml
│   └── test.yaml
└── tox.ini

7 directories, 61 files

# 将/root/.ansible/roles/ansible-network.cloud_vpn加入到ansible配置文件中就能使用roles了
[root@mmx_ansible file-template]# cat ansible.cfg
[defaults]
inventory = inventory
roles_path = /root/.ansible/roles/

[root@mmx_ansible file-template]# ansible-galaxy list
# /root/.ansible/roles
- ansible-network.cloud_vpn, v2.7.1
举报

相关推荐

0 条评论