Ansible04-Ansible Vars变量详解

目录

  • 写在前面
  • 6 Ansible Vars 变量
    • 6.1 playbook中的变量
      • 6.1.1 playbook中定义变量的格式
      • 6.1.2 举例
      • 6.1.3 小tip
    • 6.2 共有变量
      • 6.2.1 变量文件
        • 6.2.1.1 变量文件编写
        • 6.2.1.2 playbook编写
        • 6.2.1.3 运行测试
      • 6.2.2 根据主机组使用变量
        • 6.2.2.1 groups_vars编写
        • 6.2.2.2 playbook编写
        • 6.2.2.3 测试
    • 6.3 register变量
      • 6.3.1 register使用
      • 6.3.2 register变量输出的解释-json
      • 6.3.3 仅获取需要的输出
    • 6.4 facts变量
      • 6.4.1 setup模块获取的facts变量
      • 6.4.2 常用的facts变量
      • 6.4.3 facts变量的实际案例

写在前面

这是Ansible系列第四篇,内容为Ansible Vars的介绍、使用
序号连续上篇笔记 Ansible03-Ansible Playbook剧本详解

回顾一下Ansible架构:
在这里插入图片描述

6 Ansible Vars 变量

类似于shell脚本的变量,但语法格式不同.
在yaml文件中的位置一般处于tasks之上,级别同级,key为vars,也可以通过变量文件引入,key为vars_files

可以定义变量的地方说明
在剧本文件中定义比较常用。仅仅限于当前的play使用。
register变量(注册变量)`ip=hostname -I 实现脚本中反引号的功能,可以获取命令结果。
变量文件(根据主机清单分分组进行定义变量。)如果多个剧本,使用相同的变量,大型的剧本roles。
inventory主机清单中定义变量未来可以用于批量修改主机使用,其他很少用了。
命令行中几乎不用。
facts变量一般用于获取主机基本信息:ip、主机名、系统(centos/ubuntu)。如果不需要可以关闭,用于加速剧本的执行。

6.1 playbook中的变量

6.1.1 playbook中定义变量的格式

-hosts: allvars: 变量名1:变量名2:...

6.1.2 举例

#playbook
[root@manager playbook]# cat 05.pbvars.yaml
- hosts: frontvars:my_var: "Hello, World!"tasks:- name: Use playbook-defined variabledebug:msg: "{{ my_var }}"
- hosts: managervars:my_var: "Hello, World!"tasks:- name: Use playbook-defined variabledebug:msg: "{{ my_var }}"# 运行
[root@manager playbook]# ansible-playbook 05.pbvars.yamlPLAY [front] **********************************************************************************************TASK [Gathering Facts] ************************************************************************************
ok: [192.168.100.148]TASK [Use playbook-defined variable] **********************************************************************
ok: [192.168.100.148] => {"msg": "Hello, World!"
}PLAY [manager] ********************************************************************************************TASK [Gathering Facts] ************************************************************************************
ok: [192.168.100.151]TASK [Use playbook-defined variable] **********************************************************************
ok: [192.168.100.151] => {"msg": "Hello, World!"
}PLAY RECAP ************************************************************************************************
192.168.100.148            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
192.168.100.151            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

6.1.3 小tip

使用变量的时候如果变量是某个选项的开头,则变量引用的时候需要加上双引号.

dir: /oldboy/lidao/upload/
file:
path: "{{ dir }}"            #这种要添加,变量是开头.
file:
path: /oldboy-new/{{ dir }}  #这种可以不加引号,变量不是开头.
  • 在剧本play中定义变量应用:
  1. 仅仅在当前play生效.
  2. 一般用来存放路径,用户名,ip地址,类似于之前使用的脚本.
  3. 注意引号使用.

6.2 共有变量

可以被多个playbook访问的公用变量

6.2.1 变量文件

6.2.1.1 变量文件编写
[root@manager playbook]# cat vars.yml
user: www
dir: /tmp/varstest
file: /etc/hosts
6.2.1.2 playbook编写
[root@manager playbook]# cat 06.vars-file.yaml
- hosts: frontvars_files: ./vars.ymltasks:- name: 显示内容debug:msg: "vars_file内的内容{{user}} {{dir}} {{file}}"
6.2.1.3 运行测试
[root@manager playbook]# ansible-playbook 06.vars-file.yamlPLAY [front] **********************************************************************************************TASK [Gathering Facts] ************************************************************************************
ok: [192.168.100.148]TASK [显示内容] *******************************************************************************************
ok: [192.168.100.148] => {"msg": "vars_file内的内容www /tmp/varstest /etc/hosts"
}PLAY RECAP ************************************************************************************************
192.168.100.148            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

6.2.2 根据主机组使用变量

可以playbook不引入vars_file,根据主机清单自动匹配,使用group_vars提前创建好对应关系。
步骤:

  1. 在playbook文件同级目录下创建目录group_vars
  2. 创建目录主机组名/变量文件,如下:
tree -F
├── xxxx.yaml
├── group_vars/
│   │── all/
│   │   └── vars.yml
│   │── lb/
│   │   └── vars2.yml
│   └── data/
│       └── vars3.yml
└── vars.yml
#一般最常用all,把所有变量直接给所有主机组用
6.2.2.1 groups_vars编写
[root@manager playbook]# cat group_vars/all/vars.yml
user: testforgroup_vars
nfs_dir: /nfs_backup
web_mount_dir: /web_nfs
nfs_server: storage
[root@manager playbook]# tree -F
.
├── 07.group_vars.yaml
├── group_vars/└── all/└── vars.yml
6.2.2.2 playbook编写
[root@manager playbook]# cat 07.group_vars.yaml
- hosts: fronttasks:- name: 显示内容debug:msg: "vars_file内的内容{{user}} {{nfs_dir}} {{nfs_server}}"
6.2.2.3 测试
[root@manager playbook]# ansible-playbook 07.group_vars.yamlPLAY [front] **********************************************************************************************TASK [Gathering Facts] ************************************************************************************
ok: [192.168.100.148]TASK [显示内容] *******************************************************************************************
ok: [192.168.100.148] => {"msg": "vars_file内的内容testforgroup_vars /nfs_backup storage"
}PLAY RECAP ************************************************************************************************
192.168.100.148            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

6.3 register变量

本质上就是用来实现脚本中的 反引号功能 . ip=hostname -I
用户通过命令获取的内容都存放到Register变量中.

  • 用法:
#在模块下使用 register: 变量名 的方式
- name: get dateshell: date +%Fregister: result
#使用register变量
- name: debugdebug:msg: "date的结果:{{result}}"

6.3.1 register使用

#编写playbook
[root@manager playbook]# cat 08.register.yaml
- hosts: fronttasks:- name: get dateshell: date +%Fregister: result #register: 变量名,接受上面的模块的结果- name: debugdebug:msg: "date的命令结果:{{result}}" #使用变量名即可# 测试
[root@manager playbook]# ansible-playbook 08.register.yamlPLAY [front] **********************************************************************************************TASK [Gathering Facts] ************************************************************************************
ok: [192.168.100.148]TASK [get date] *******************************************************************************************
changed: [192.168.100.148]TASK [debug] **********************************************************************************************
ok: [192.168.100.148] => {"msg": "date的命令结果:{'changed': True, 'stdout': '2024-05-29', 'stderr': '', 'rc': 0, 'cmd': 'date +%F', 'start': '2024-05-29 13:53:07.655923', 'end': '2024-05-29 13:53:07.665129', 'delta': '0:00:00.009206', 'msg': '', 'stdout_lines': ['2024-05-29'], 'stderr_lines': [], 'failed': False}"
}PLAY RECAP ************************************************************************************************
192.168.100.148            : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

6.3.2 register变量输出的解释-json

{'changed': True, 'stdout': '2024-05-29', 'stderr': '', 'rc': 0, 'cmd': 'date +%F', 'start': '2024-05-29 13:53:07.655923', 'end': '2024-05-29 13:53:07.665129', 'delta': '0:00:00.009206', 'msg': '', 'stdout_lines': ['2024-05-29'], 'stderr_lines': [], 'failed': False}

6.3.3 仅获取需要的输出

#修改playbook
[root@manager playbook]# cat 08.register.yaml
- hosts: fronttasks:- name: get dateshell: date +%Fregister: result- name: debugdebug:msg: "date的命令结果:{{result.stdout}}" #变量名.stdout可以仅输出需要的内容stdout_lines#测试
[root@manager playbook]# ansible-playbook 08.register.yamlPLAY [front] **********************************************************************************************TASK [Gathering Facts] ************************************************************************************
ok: [192.168.100.148]TASK [get date] *******************************************************************************************
changed: [192.168.100.148]TASK [debug] **********************************************************************************************
ok: [192.168.100.148] => {"msg": "date的命令结果:2024-05-29"
}PLAY RECAP ************************************************************************************************
192.168.100.148            : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

6.4 facts变量

ansible的内置变量,playbook运行时有一个默认的task。用于收集每个主机的基本信息。
信息包括ip主机名磁盘……
facts变量的值可以通过setup模块获取,返回值为json。

6.4.1 setup模块获取的facts变量

[2024-05-30 22:07:40]  [root@manager ~]# ansible front -m pingstetup
[2024-05-30 22:07:46]  192.168.100.148 | SUCCESS => {"ansible_facts": {"ansible_all_ipv4_addresses": ["192.168.100.148"],"ansible_all_ipv6_addresses": ["fe80::20c:29ff:fe8c:f581"],"ansible_apparmor": {"status": "disabled"},"ansible_architecture": "x86_64","ansible_bios_date": "07/22/2020","ansible_bios_vendor": "Phoenix Technologies LTD","ansible_bios_version": "6.00","ansible_board_asset_tag": "NA","ansible_board_name": "440BX Desktop Reference Platform","ansible_board_serial": "None","ansible_board_vendor": "Intel Corporation","ansible_board_version": "None","ansible_chassis_asset_tag": "No Asset Tag","ansible_chassis_serial": "None","ansible_chassis_vendor": "No Enclosure","ansible_chassis_version": "N/A","ansible_cmdline": {"BOOT_IMAGE": "(hd0,msdos1)/vmlinuz-4.18.0-448.el8.x86_64","crashkernel": "auto","quiet": true,"rd.lvm.lv": "cs/swap","resume": "/dev/mapper/cs-swap","rhgb": true,"ro": true,"root": "/dev/mapper/cs-root"},"ansible_date_time": {"date": "2024-05-30","day": "30","epoch": "1717078069","epoch_int": "1717078069","hour": "22","iso8601": "2024-05-30T14:07:49Z","iso8601_basic": "20240530T220749250313","iso8601_basic_short": "20240530T220749","iso8601_micro": "2024-05-30T14:07:49.250313Z","minute": "07","month": "05","second": "49","time": "22:07:49","tz": "CST","tz_dst": "CST","tz_offset": "+0800","weekday": "Thursday","weekday_number": "4","weeknumber": "22","year": "2024"},"ansible_default_ipv4": {"address": "192.168.100.148","alias": "ens33","broadcast": "192.168.100.255","gateway": "192.168.100.2","interface": "ens33","macaddress": "00:0c:29:8c:f5:81","mtu": 1500,"netmask": "255.255.255.0","network": "192.168.100.0","prefix": "24","type": "ether"},"ansible_default_ipv6": {},"ansible_device_links": {"ids": {"dm-0": ["dm-name-cs-root","dm-uuid-LVM-XM02qL1zmnDg1RigchdScO0PQwIlGGrmKZUJdkfQCHUDHDmaKXBWS7ddjTvylC6c"],"dm-1": ["dm-name-cs-swap","dm-uuid-LVM-XM02qL1zmnDg1RigchdScO0PQwIlGGrm2MfDkEHILjM7IfU0FWqw6BpsIUAOJUks"],"dm-2": ["dm-name-cs-home","dm-uuid-LVM-XM02qL1zmnDg1RigchdScO0PQwIlGGrm9UrYudORKil6vGwk0NMl4QHREXI9CCft"],"sda2": ["lvm-pv-uuid-1Hyexv-eeJS-2Chi-Ack1-Qddg-90GS-QXw1qW"],"sr0": ["ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"]},"labels": {},"masters": {"sda2": ["dm-0","dm-1","dm-2"]},"uuids": {"dm-0": ["a712c91e-8b89-42e0-9ce6-16e88a49bf95"],"dm-1": ["11a5a2e7-9628-417e-b7f7-5df4e0ea9a1b"],"dm-2": ["4c41ab60-f8e9-4167-84c4-c258f4fd3824"],"sda1": ["e2e2cd86-5a1f-4c24-95d6-2ae74ed3f976"]}},"ansible_devices": {"dm-0": {"holders": [],"host": "","links": {"ids": ["dm-name-cs-root","dm-uuid-LVM-XM02qL1zmnDg1RigchdScO0PQwIlGGrmKZUJdkfQCHUDHDmaKXBWS7ddjTvylC6c"],"labels": [],"masters": [],"uuids": ["a712c91e-8b89-42e0-9ce6-16e88a49bf95"]},"model": null,"partitions": {},"removable": "0","rotational": "1","sas_address": null,"sas_device_handle": null,"scheduler_mode": "","sectors": "133955584","sectorsize": "512","size": "63.88 GB","support_discard": "0","vendor": null,"virtual": 1},"dm-1": {"holders": [],"host": "","links": {"ids": ["dm-name-cs-swap","dm-uuid-LVM-XM02qL1zmnDg1RigchdScO0PQwIlGGrm2MfDkEHILjM7IfU0FWqw6BpsIUAOJUks"],"labels": [],"masters": [],"uuids": ["11a5a2e7-9628-417e-b7f7-5df4e0ea9a1b"]},"model": null,"partitions": {},"removable": "0","rotational": "1","sas_address": null,"sas_device_handle": null,"scheduler_mode": "","sectors": "8249344","sectorsize": "512","size": "3.93 GB","support_discard": "0","vendor": null,"virtual": 1},"dm-2": {"holders": [],"host": "","links": {"ids": ["dm-name-cs-home","dm-uuid-LVM-XM02qL1zmnDg1RigchdScO0PQwIlGGrm9UrYudORKil6vGwk0NMl4QHREXI9CCft"],"labels": [],"masters": [],"uuids": ["4c41ab60-f8e9-4167-84c4-c258f4fd3824"]},"model": null,"partitions": {},"removable": "0","rotational": "1","sas_address": null,"sas_device_handle": null,"scheduler_mode": "","sectors": "65404928","sectorsize": "512","size": "31.19 GB","support_discard": "0","vendor": null,"virtual": 1},"sda": {"holders": [],"host": "SCSI storage controller: Broadcom / LSI 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)","links": {"ids": [],"labels": [],"masters": [],"uuids": []},"model": "VMware Virtual S","partitions": {"sda1": {"holders": [],"links": {"ids": [],"labels": [],"masters": [],"uuids": ["e2e2cd86-5a1f-4c24-95d6-2ae74ed3f976"]},"sectors": "2097152","sectorsize": 512,"size": "1.00 GB","start": "2048","uuid": "e2e2cd86-5a1f-4c24-95d6-2ae74ed3f976"},"sda2": {"holders": ["cs-swap","cs-home","cs-root"],"links": {"ids": ["lvm-pv-uuid-1Hyexv-eeJS-2Chi-Ack1-Qddg-90GS-QXw1qW"],"labels": [],"masters": ["dm-0","dm-1","dm-2"],"uuids": []},"sectors": "207616000","sectorsize": 512,"size": "99.00 GB","start": "2099200","uuid": null}},"removable": "0","rotational": "1","sas_address": null,"sas_device_handle": null,"scheduler_mode": "mq-deadline","sectors": "209715200","sectorsize": "512","size": "100.00 GB","support_discard": "0","vendor": "VMware,","virtual": 1},"sr0": {"holders": [],"host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)","links": {"ids": ["ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"],"labels": [],"masters": [],"uuids": []},"model": "VMware IDE CDR10","partitions": {},"removable": "1","rotational": "1","sas_address": null,"sas_device_handle": null,"scheduler_mode": "mq-deadline","sectors": "2097151","sectorsize": "512","size": "1024.00 MB","support_discard": "0","vendor": "NECVMWar","virtual": 1}},"ansible_distribution": "CentOS","ansible_distribution_file_parsed": true,"ansible_distribution_file_path": "/etc/centos-release","ansible_distribution_file_variety": "CentOS","ansible_distribution_major_version": "8","ansible_distribution_release": "Stream","ansible_distribution_version": "8","ansible_dns": {"nameservers": ["192.168.100.2"],"search": ["localdomain"]},"ansible_domain": "","ansible_effective_group_id": 0,"ansible_effective_user_id": 0,"ansible_ens33": {"active": true,"device": "ens33","features": {"esp_hw_offload": "off [fixed]","esp_tx_csum_hw_offload": "off [fixed]","fcoe_mtu": "off [fixed]","generic_receive_offload": "on","generic_segmentation_offload": "on","highdma": "off [fixed]","hw_tc_offload": "off [fixed]","l2_fwd_offload": "off [fixed]","large_receive_offload": "off [fixed]","loopback": "off [fixed]","netns_local": "off [fixed]","ntuple_filters": "off [fixed]","receive_hashing": "off [fixed]","rx_all": "off","rx_checksumming": "off","rx_fcs": "off","rx_gro_hw": "off [fixed]","rx_gro_list": "off","rx_udp_gro_forwarding": "off","rx_udp_tunnel_port_offload": "off [fixed]","rx_vlan_filter": "on [fixed]","rx_vlan_offload": "on","rx_vlan_stag_filter": "off [fixed]","rx_vlan_stag_hw_parse": "off [fixed]","scatter_gather": "on","tcp_segmentation_offload": "on","tls_hw_record": "off [fixed]","tls_hw_rx_offload": "off [fixed]","tls_hw_tx_offload": "off [fixed]","tx_checksum_fcoe_crc": "off [fixed]","tx_checksum_ip_generic": "on","tx_checksum_ipv4": "off [fixed]","tx_checksum_ipv6": "off [fixed]","tx_checksum_sctp": "off [fixed]","tx_checksumming": "on","tx_esp_segmentation": "off [fixed]","tx_fcoe_segmentation": "off [fixed]","tx_gre_csum_segmentation": "off [fixed]","tx_gre_segmentation": "off [fixed]","tx_gso_list": "off [fixed]","tx_gso_partial": "off [fixed]","tx_gso_robust": "off [fixed]","tx_ipxip4_segmentation": "off [fixed]","tx_ipxip6_segmentation": "off [fixed]","tx_lockless": "off [fixed]","tx_nocache_copy": "off","tx_scatter_gather": "on","tx_scatter_gather_fraglist": "off [fixed]","tx_sctp_segmentation": "off [fixed]","tx_tcp6_segmentation": "off [fixed]","tx_tcp_ecn_segmentation": "off [fixed]","tx_tcp_mangleid_segmentation": "off","tx_tcp_segmentation": "on","tx_tunnel_remcsum_segmentation": "off [fixed]","tx_udp_segmentation": "off [fixed]","tx_udp_tnl_csum_segmentation": "off [fixed]","tx_udp_tnl_segmentation": "off [fixed]","tx_vlan_offload": "on [fixed]","tx_vlan_stag_hw_insert": "off [fixed]","vlan_challenged": "off [fixed]"},"hw_timestamp_filters": [],"ipv4": {"address": "192.168.100.148","broadcast": "192.168.100.255","netmask": "255.255.255.0","network": "192.168.100.0","prefix": "24"},"ipv6": [{"address": "fe80::20c:29ff:fe8c:f581","prefix": "64","scope": "link"}],"macaddress": "00:0c:29:8c:f5:81","module": "e1000","mtu": 1500,"pciid": "0000:02:01.0","promisc": false,"speed": 1000,"timestamping": [],"type": "ether"},"ansible_env": {"BASH_FUNC_which%%": "() {  ( alias;\n eval ${which_declare} ) | /usr/bin/which --tty-only --read-alias --read-functions --show-tilde --show-dot $@\n}","DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/0/bus","DEBUGINFOD_URLS": "https://debuginfod.centos.org/ ","HOME": "/root","LANG": "en_US.UTF-8","LESSOPEN": "||/usr/bin/lesspipe.sh %s","LOGNAME": "root","LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.m4a=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.oga=01;36:*.opus=01;36:*.spx=01;36:*.xspf=01;36:","PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin","PWD": "/root","SELINUX_LEVEL_REQUESTED": "","SELINUX_ROLE_REQUESTED": "","SELINUX_USE_CURRENT_RANGE": "","SHELL": "/bin/bash","SHLVL": "2","SSH_CLIENT": "192.168.100.151 60220 22","SSH_CONNECTION": "192.168.100.151 60220 192.168.100.148 22","SSH_TTY": "/dev/pts/0","TERM": "xterm","USER": "root","XDG_RUNTIME_DIR": "/run/user/0","XDG_SESSION_ID": "1","_": "/usr/libexec/platform-python","which_declare": "declare -f"},"ansible_fibre_channel_wwn": [],"ansible_fips": false,"ansible_form_factor": "Other","ansible_fqdn": "front","ansible_hostname": "front","ansible_hostnqn": "","ansible_interfaces": ["ens33","lo"],"ansible_is_chroot": false,"ansible_iscsi_iqn": "","ansible_kernel": "4.18.0-448.el8.x86_64","ansible_kernel_version": "#1 SMP Wed Jan 18 15:02:46 UTC 2023","ansible_lo": {"active": true,"device": "lo","features": {"esp_hw_offload": "off [fixed]","esp_tx_csum_hw_offload": "off [fixed]","fcoe_mtu": "off [fixed]","generic_receive_offload": "on","generic_segmentation_offload": "on","highdma": "on [fixed]","hw_tc_offload": "off [fixed]","l2_fwd_offload": "off [fixed]","large_receive_offload": "off [fixed]","loopback": "on [fixed]","netns_local": "on [fixed]","ntuple_filters": "off [fixed]","receive_hashing": "off [fixed]","rx_all": "off [fixed]","rx_checksumming": "on [fixed]","rx_fcs": "off [fixed]","rx_gro_hw": "off [fixed]","rx_gro_list": "off","rx_udp_gro_forwarding": "off","rx_udp_tunnel_port_offload": "off [fixed]","rx_vlan_filter": "off [fixed]","rx_vlan_offload": "off [fixed]","rx_vlan_stag_filter": "off [fixed]","rx_vlan_stag_hw_parse": "off [fixed]","scatter_gather": "on","tcp_segmentation_offload": "on","tls_hw_record": "off [fixed]","tls_hw_rx_offload": "off [fixed]","tls_hw_tx_offload": "off [fixed]","tx_checksum_fcoe_crc": "off [fixed]","tx_checksum_ip_generic": "on [fixed]","tx_checksum_ipv4": "off [fixed]","tx_checksum_ipv6": "off [fixed]","tx_checksum_sctp": "on [fixed]","tx_checksumming": "on","tx_esp_segmentation": "off [fixed]","tx_fcoe_segmentation": "off [fixed]","tx_gre_csum_segmentation": "off [fixed]","tx_gre_segmentation": "off [fixed]","tx_gso_list": "on","tx_gso_partial": "off [fixed]","tx_gso_robust": "off [fixed]","tx_ipxip4_segmentation": "off [fixed]","tx_ipxip6_segmentation": "off [fixed]","tx_lockless": "on [fixed]","tx_nocache_copy": "off [fixed]","tx_scatter_gather": "on [fixed]","tx_scatter_gather_fraglist": "on [fixed]","tx_sctp_segmentation": "on","tx_tcp6_segmentation": "on","tx_tcp_ecn_segmentation": "on","tx_tcp_mangleid_segmentation": "on","tx_tcp_segmentation": "on","tx_tunnel_remcsum_segmentation": "off [fixed]","tx_udp_segmentation": "on","tx_udp_tnl_csum_segmentation": "off [fixed]","tx_udp_tnl_segmentation": "off [fixed]","tx_vlan_offload": "off [fixed]","tx_vlan_stag_hw_insert": "off [fixed]","vlan_challenged": "on [fixed]"},"hw_timestamp_filters": [],"ipv4": {"address": "127.0.0.1",                  "broadcast": "",                  "netmask": "255.0.0.0",                  "network": "127.0.0.0",                  "prefix": "8"              },              "ipv6": [                  {                      "address": "::1",                      "prefix": "128",                      "scope": "host"                  }              ],              "mtu": 65536,              "promisc": false,"timestamping": [],"type": "loopback"},"ansible_loadavg": {"15m": 0.1,"1m": 0.2,"5m": 0.22},"ansible_local": {},"ansible_locally_reachable_ips": {"ipv4": ["127.0.0.0/8","127.0.0.1","192.168.100.148"],"ipv6": ["::1","fe80::20c:29ff:fe8c:f581"]},"ansible_lsb": {},"ansible_lvm": {"lvs": {"home": {"size_g": "31.19","vg": "cs"},"root": {"size_g": "63.88","vg": "cs"},"swap": {"size_g": "3.93","vg": "cs"}},"pvs": {"/dev/sda2": {"free_g": "0","size_g": "99.00","vg": "cs"}},"vgs": {"cs": {"free_g": "0","num_lvs": "3","num_pvs": "1","size_g": "99.00"}}},"ansible_machine": "x86_64","ansible_machine_id": "ac3f85584fd24fd9b7d050a72e7917ce","ansible_memfree_mb": 3218,"ansible_memory_mb": {"nocache": {"free": 3386,"used": 254},"real": {"free": 3218,"total": 3640,"used": 422},"swap": {"cached": 0,"free": 4027,"total": 4027,"used": 0}},"ansible_memtotal_mb": 3640,"ansible_mounts": [{"block_available": 16136568,"block_size": 4096,"block_total": 16736272,"block_used": 599704,"device": "/dev/mapper/cs-root","fstype": "xfs","inode_available": 33448136,"inode_total": 33488896,"inode_used": 40760,"mount": "/","options": "rw,seclabel,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota","size_available": 66095382528,"size_total": 68551770112,"uuid": "a712c91e-8b89-42e0-9ce6-16e88a49bf95"},{"block_available": 203832,"block_size": 4096,"block_total": 259584,"block_used": 55752,"device": "/dev/sda1","fstype": "xfs","inode_available": 523978,"inode_total": 524288,"inode_used": 310,"mount": "/boot","options": "rw,seclabel,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota","size_available": 834895872,"size_total": 1063256064,"uuid": "e2e2cd86-5a1f-4c24-95d6-2ae74ed3f976"},{"block_available": 8106380,"block_size": 4096,"block_total": 8171624,"block_used": 65244,"device": "/dev/mapper/cs-home","fstype": "xfs","inode_available": 16351224,"inode_total": 16351232,"inode_used": 8,"mount": "/home","options": "rw,seclabel,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota","size_available": 33203732480,"size_total": 33470971904,"uuid": "4c41ab60-f8e9-4167-84c4-c258f4fd3824"}],"ansible_nodename": "front","ansible_os_family": "RedHat","ansible_pkg_mgr": "dnf","ansible_proc_cmdline": {"BOOT_IMAGE": "(hd0,msdos1)/vmlinuz-4.18.0-448.el8.x86_64","crashkernel": "auto","quiet": true,"rd.lvm.lv": ["cs/root","cs/swap"],"resume": "/dev/mapper/cs-swap","rhgb": true,"ro": true,"root": "/dev/mapper/cs-root"},"ansible_processor": ["0","GenuineIntel","13th Gen Intel(R) Core(TM) i5-1340P","1","GenuineIntel","13th Gen Intel(R) Core(TM) i5-1340P"],"ansible_processor_cores": 2,"ansible_processor_count": 1,"ansible_processor_nproc": 2,"ansible_processor_threads_per_core": 1,"ansible_processor_vcpus": 2,"ansible_product_name": "VMware Virtual Platform","ansible_product_serial": "VMware-56 4d 8f 62 7b d2 12 a4-ee d7 c9 ef 44 8c f5 81","ansible_product_uuid": "628f4d56-d27b-a412-eed7-c9ef448cf581","ansible_product_version": "None","ansible_python": {"executable": "/usr/libexec/platform-python","has_sslcontext": true,"type": "cpython","version": {"major": 3,"micro": 8,"minor": 6,"releaselevel": "final","serial": 0},"version_info": [3,6,8,"final",0]},"ansible_python_version": "3.6.8","ansible_real_group_id": 0,"ansible_real_user_id": 0,"ansible_selinux": {"config_mode": "enforcing","mode": "enforcing","policyvers": 33,"status": "enabled","type": "targeted"},"ansible_selinux_python_present": true,"ansible_service_mgr": "systemd","ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFxnKOqZYpwyrGNtXfZE3PszuzzTGi+MHAQLdIdrdqLQD/ssIywmk2zaGkhdBgduODbKHZFIc3StPq2zIFWgQcI=","ansible_ssh_host_key_ecdsa_public_keytype": "ecdsa-sha2-nistp256","ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIPrloLDFnE3ApAlo0stYWeqjZwQb5r8wG41F6p4BNONV","ansible_ssh_host_key_ed25519_public_keytype": "ssh-ed25519","ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABgQC74yocPMpe5Na1cbnv6LSvAGnIPwWucMAoI1WfY69o31WHShckwT8VCs41a0xBQAjqdCSo5WlP+LqJWzO/AjZMQU0CRfpF8WsW5P21QaNOVSnEJGve3eZEixkpgaQGthu9nPAtY97ctWHa599Ni2rpuKXRWr+qQ6PX5Co/HXtavJBkvsSSeaN1SmDUfg/0k505NtoGHDTLWghxuXcY2ROMhLaRbAwG7/kIJknc6tvwnViCscPcNSPbZs36eynIk1S5CpOgYWr9PIDECghKrgU/mn3Rs892OT2W+VOIlx1i3Vz4fnONXA843LZ25qG/76lGtpWzvVx7dWyOcgeTFRIyHNC5U28d1hWTGerKwgiNC6ATF8CJgsstFwIqtOMEBEdVpaJ5e0jdnf0z0db0N9POr3txau4GeYIMCItgygmehDfMwoqFhKSHuaJfhd154V1ie9y61xdhhch/w6Bv8wfEfUiKxX2LhwaMdPVvPDVBSOAmtfNM/OrKcJiIe9O5i0M=","ansible_ssh_host_key_rsa_public_keytype": "ssh-rsa","ansible_swapfree_mb": 4027,"ansible_swaptotal_mb": 4027,"ansible_system": "Linux","ansible_system_capabilities": [],"ansible_system_capabilities_enforced": "False","ansible_system_vendor": "VMware, Inc.","ansible_uptime_seconds": 249,"ansible_user_dir": "/root","ansible_user_gecos": "root","ansible_user_gid": 0,"ansible_user_id": "root","ansible_user_shell": "/bin/bash","ansible_user_uid": 0,"ansible_userspace_architecture": "x86_64","ansible_userspace_bits": "64","ansible_virtualization_role": "guest","ansible_virtualization_tech_guest": ["VMware"],"ansible_virtualization_tech_host": ["kvm"],"ansible_virtualization_type": "VMware","discovered_interpreter_python": "/usr/libexec/platform-python","gather_subset": ["all"],"module_setup": true},"changed": false}

6.4.2 常用的facts变量

ansible_hostname   #主机名
ansible_memtotal_mb #内存大小(总计) 单位mb 
ansible_processor_vcpus        #cpu数量
ansible_default_ipv4.address   #默认的网卡ip eth0
ansible_distribution           #系统发行版本名字
CentOS Ubuntu Debian ……
ansible_processor_vcpus 
ansible_processor_cores
ansible_date_time.date

6.4.3 facts变量的实际案例

  1. 通过facts变量获取系统的基本信息
  2. 通过facts变量获取信息并进行判断
  3. 如果不需要可以进行关闭,加速剧本的运行(hosts行下一行添加gather_facts: no)
- hosts: frontgather_facts: notasks: 
.....
  • 批量修改系统/etc/motd文件(登陆时自动显示的文件)
    • 输出主机名
    • 内存大小
    • ip
    • 发行版本
    • cpu数量
    • 核心数量
#playbook编写
[root@manager playbook]# cat 10.change_moted.yaml
- hosts: fronttasks:- name: template分发motdtemplate:src: templates/motd.j2dest: /etc/motdbackup: yes#    - name: cp分发motd#      copy:#        src: templates/motd.j2#        dest: /etc/motd#        backup: yes# motd.j2模板编写
[root@manager templates]# cat motd.j2
welcome to Linux-{{ ansible_hostname }}
--------------------------------------------
主机名: {{ ansible_hostname }}
ip地址: {{ ansible_default_ipv4.address }}
内存大小: {{ ansible_memtotal_mb }}
CPU数量: {{ ansible_processor_vcpus }}
核心总数: {{ ansible_processor_cores }}
发行版本: {{ ansible_distribution }}#运行
[root@manager playbook]# ansible-playbook 10.change_moted.yamlPLAY [front] **********************************************************************************************TASK [Gathering Facts] ************************************************************************************
ok: [192.168.100.148]TASK [template分发motd] ***********************************************************************************
changed: [192.168.100.148]PLAY RECAP ************************************************************************************************
192.168.100.148            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0# 测试
[root@manager playbook]# ssh root@front
welcome to Linux-front
--------------------------------------------
主机名: front
ip地址: 192.168.100.148
内存大小: 3640
CPU数量: 2
核心总数: 2
发行版本: CentOS

template和copy模块的区别:
copy仅仅传输数据,复制文件;
template 传输数据,复制文件的时候,文件中的变量会被解析和运行.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/20063.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

迈的普拉姆利普绘图:深入解析与实战应用

新书上架~👇全国包邮奥~ python实用小工具开发教程http://pythontoolsteach.com/3 欢迎关注我👆,收藏下次不迷路┗|`O′|┛ 嗷~~ 目录 一、引言:matplotlib绘图的基本原理 代码案例 二、深入了解:matplo…

数据结构与算法02-排序算法

介绍 排序算法是计算机科学中被广泛研究的一个课题。历时多年,它发展出了数十种算法,这些 算法都着眼于一个问题:如何将一个无序的数字数组整理成升序?先来学习一些“简单排序”,它们很好懂,但效率不如其他…

闽盾杯 2021 DNS协议分析

今年CISCN的Tough DNS 的前戏就是DNS协议分析 直接可以查找到flag的base64形式Zmxh 发现就是请求的dnslog 携带的数据 过滤器就是 dns tshark -r dns.pcapng -T json -Y "dns" >1.json 字段选择 dns.qry.name tshark -r dns.pcapng -T json -Y "dns"…

内网渗透-隧道搭建ssp隧道代理工具

内网渗透-隧道搭建&ssp隧道代理工具 目录 内网渗透-隧道搭建&ssp隧道代理工具spp隧道代理工具spp工作原理图cs上线主机spp代理通信服务端配置客户端配置CS配置设置CS生成木马的监听器配置CS监听上线的监听器生成木马 spp隧道搭建服务端配置客户端配置CS配置 内网穿透&a…

根据模板和git commit自动生成日·周·月·季报

GitHub - qiaotaizi/dailyreport: 日报生成器 GitHub - yurencloud/daily: 程序员专用的日报、周报、月报、季报自动生成器! config.json: { "Author": "gitname", "Exclude": ["update:", "add:", "…

实际测试stm32中断优先级

HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); void HAL_NVIC_DisableIRQ(IRQn_Type IRQn);第一个函数 HAL_NVIC_SetPriority 是用来设置单个优先级的抢占优先级和响应优先级的值。第二个…

恒压频比开环控制系统Matlab/Simulink仿真分析(SPWM控制方式)

介绍恒压频比的开环控制方法驱动永磁同步电机的转动,首先分析恒压频比的控制原理,然后在Matlab/Simulink中进行永磁同步电机恒压频比开环控制系统的仿真分析,最后将Simulink中的恒压频比控制算法生成代码加载到实际工程中进行工程实现。 一、…

丝绸之路网络安全论坛成功举办,开源网安受邀分享软件供应链安全落地经验

5月23日,2024第八届丝绸之路网络安全论坛在陕西宾馆会议中心成功举办,本次论坛由陕西省信息网络安全协会主办,以“汇聚万千智慧 夯实安全堤坝”为主题,邀请业内专家学者、企业代表、行业代表共计400余人参加。开源网安常务副总王颉…

【PostgreSQL17新特性之-冗余IS [NOT] NULL限定符的处理优化】

在执行一个带有IS NOT NULL或者NOT NULL的SQL的时候,通常会对表的每一行,都会进行检查以确保列为空/不为空,这是符合常理的。 但是如果本身这个列上有非空(NOT NULL)约束,再次检查就会浪费资源。甚至有时候…

Leetcode3165. 不包含相邻元素的子序列的最大和(Go中的线段树分治包含多类数据使用maintain进行维护)

题目截图 题目分析 不能取相邻的,就是打家劫舍 然后更改某一个值就是单点更新 更新后,需要更新区间的值 需要注意的是,使用分治时需要考虑到一头一尾的问题,所以有4种情况(选or不选在两个位置) 这四种情况…

编程入门(七)【虚拟机VMware安装Linux系统Ubuntu】

读者大大们好呀!!!☀️☀️☀️ 🔥 欢迎来到我的博客 👀期待大大的关注哦❗️❗️❗️ 🚀欢迎收看我的主页文章➡️寻至善的主页 文章目录 🔥前言🚀Ubuntu知多少🚀安装的前期准备&am…

SQL—DQL之执行顺序(基础)

一、引言 1、编写顺序 2、执行顺序 介绍: DQL语句(数据查询语句) 1、首先先执行的是 FROM ,通过 FROM 来决定我要查询的是哪一张表的数据。 2、紧接着通过 WHERE 来指定查询的条件。 3、第三步就是通过 GROUP BY 以及 HAVING 来…

中国BI步入增长大周期,腾讯云ChatBI加速AI+BI融合

过去十年,大数据技术的快速发展,让数据消费前进一大步,数据价值得到一定程度的挖掘与释放,真正开启了“用数”的大时代。但数据分析繁杂的技术栈、复杂的处理过程以及程式化的交互方式,让“数据消费”的门槛始终降不下…

现在的时代,您必会的“调教”AI技巧

人工智能大行其道,如何借势?始于问询。要得要得预期,精于“提问技巧”! (笔记模板由python脚本于2024年05月30日 18:37:27创建,本篇笔记适合有独立编程基础的coder翻阅) 【学习的细节是欢悦的历程】 Python 官网&#…

基于 Apache Doris 的实时/离线一体化架构,赋能中国联通 5G 全连接工厂解决方案

作者:田向阳,联通西部创新研究院 大数据专家 共创:SelectDB 技术团队 导读: 数据是 5G 全连接工厂的核心要素,为支持全方位的数据收集、存储、分析等工作的高效进行,联通 5G 全连接工厂从典型的 Lambda 架…

Presto 从提交SQL到获取结果 源码详解(3)

物理执行计划 回到SqlQueryExecution.startExecution() ,执行计划划分以后, // 初始化连接,获取Connect 元数据,添加会话,初始ConnectId metadata.beginQuery(getSession(), plan.getConnectors()); // 构建物理执行…

AngularJS基础语法(2009版本)

jquery和AngularJS 数据绑定和获取对比: jquery,要操作DOM: angularJS,无需操作DOM就可以进行动态数据变化: 要使用Angularjs就需要在html页面先引入: ng-app: html页面中,需要给…

redis(17):什么是布隆过滤器?如何实现布隆过滤器?

1 布隆过滤器介绍 布隆过滤器(Bloom Filter)是一种空间效率极高的概率型数据结构,用于判断一个元素是否在一个集合中。它基于位数组和多个哈希函数的原理,可以高效地进行元素的查询,而且占用的空间相对较小,如下图所示: 根据 key 值计算出它的存储位置,然后将此位置标…

API测试工具领域,Postman的10个最佳替换

Postman 赢得了流行且有效的 API 工具的声誉。然而,对于那些寻求更符合特定需求和偏好的替代方案的人来说,存在一些值得注意的选择。这些 Postman 替代方案提供了独特的特性和功能,可满足测试过程的各个方面的需求。 在本博客中,…

如何快速的在线编辑pdf?6个软件让你轻松编辑pdf

如何快速的在线编辑pdf?6个软件让你轻松编辑pdf 在线编辑PDF文件是一项非常方便的任务,以下是六款让您轻松进行在线PDF编辑的软件: 嗨动PDF编辑器:这是一个功能强大的PDF编辑器,可以帮助您快速编辑PDF文档&#xff…