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.rhkb.cn/news/339302.html

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

相关文章

第17篇:JTAG UART IP应用<四>

Q:如何通过JTAG UART发送命令控制开发板的外设比如LED? A:Quartus硬件工程以及Platform Designer系统在第一个Nios II工程--Hello_World的Quartus硬件工程基础上添加PIO,表示DE2-115开发板上的18个红色LED。 Nios II软件工程对应…

mysql中EXPLAIN详解

大家好。众所周知,MySQL 查询优化器的各种基于成本和规则的优化会后生成一个所谓的执行计划,这个执行计划展示了接下来具体执行查询的方式。在日常工作过程中,我们可以使用EXPLAIN语句来查看某个查询语句的具体执行计划, 今天我们…

JMeter的基本使用

JMeter的基本使用三步骤:1.添加线程、2.添加请求、3.添加查询结果的内容 如果需要添加token请求头来验证,则需要再加上一步骤:添加请求头 1.线程 添加线程的方式 主要修改者三个属性值 Number of Threads:并发线程数 Ramp-up…

LabVIEW通过以太网控制PLC程序开发

在使用LabVIEW通过以太网控制PLC程序开发时,需要综合考虑硬件、软件和通信协议的协调工作。以下是详细步骤、注意事项、重点和难点分析,以及几种实现方式及其特点的概述。 实现步骤 确定硬件和软件环境: 确定PLC型号和品牌(如西门…

Java 18新特性深度解析:提升开发效率与性能的革新工具

在Java的世界中,每一次更新都带来新的惊喜和挑战。Java 18作为长期支持版本,不仅延续了Java语言的稳定性和可靠性,还引入了一系列令人兴奋的新特性,旨在进一步提升开发者的生产力和应用程序的性能。本文将深入探讨Java 18中的关键…

【一刷《剑指Offer》】面试题 29:数组中出现次数超过一半的数字

力扣对应题目链接:169. 多数元素 - 力扣(LeetCode) 牛客对应题目链接:数组中出现次数超过一半的数字_牛客题霸_牛客网 (nowcoder.com) 核心考点 : 数组使用,简单算法的设计。 一、《剑指Offer》对应内容 二…

2024后端服务架构升级

文章目录 背景改造方案新架构图技术选型思考 服务拆分公共组件设计自部署算法服务排期计划 全球多活改造背景架构图分布式ID 背景 1、xx业务经过多轮的业务决策和调整,存在非常多技术包袱,带了不好的用户体验和极高的维护成本 2、多套机房部署&#xf…

数学建模之MATLAB入门教程(上)

前言: • MATLAB是美国Math Works公司出品的商业数学软件,用于数据分析、无线通信、深度学习、图像处理与计算机视觉、信号处理、量化金融与风险管理、机器人,控制系统等领域。 • MATLAB将数值分析、矩阵计算、科学数据可视化以及非线性动…

JavaScript基础(十一)

String对象的方法 上一次说了String,那也少不了方法。 length 字符串长度 charAt(a) 返回指定位置的字符,(这里a代表下标,它返回的就是下标a对应的字符) concat(b) 连接字符串,b是被合并的对象名,和加号拼接一样…

上位机图像处理和嵌入式模块部署(f407 mcu中tf卡读写和fatfs挂载)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing 163.com】 很早之前,个人对tf卡并不是很重视,觉得它就是一个存储工具而已。后来在移植v3s芯片的时候,才发现很多的soc其实…

鬼刀画风扁平化粒子炫动引导页美化版

源码介绍 分享一款引导页,响应式布局,支持移动PC 添加背景图片,美化高斯模糊 ,删除蒙版人物部分,更图片人物画风更美好 删除雪花特效 替换字体颜色 添加底备案号 预留友情连接 效果预览 源码下载 https://www.qqmu.com/3381.h…

华为交换机的基本配置

实验拓扑: 实验目的:认识二层交换机和二层交换技术的工作原理;认识三层交换和三层交换技术。 三层功能简而言之就是了具有路由的功能,设备可以充当网关和路由器。 实验要求:公司的两个部门用vlan进行划分&#xff0c…

Redis篇 哈希表在redis中的命令

哈希命令 一.哈希表的基本认识二. 哈希表在redis中的命令1.hset,hget2.hdel3.hkeys,hvals4.hexists5.hgetall6.hmget7.hlen8.hincrby和hincrbyfloat 一.哈希表的基本认识 在JAVA数据结构中,我们就已经接触到了哈希表, 在当时,我们主要用到的哈…

ICPC训练赛补题集

ICPC训练赛补题集 文章目录 ICPC训练赛补题集D - Fast and Fat (负重越野)I-路径规划G. Inscryption(邪恶铭刻)NEW Houses雪中楼(西安交通大学)L.BracketGenerationE - Checksum D - Fast and Fat (负重越野) 原题链接:原题链接 题意:体重大的背体重小的…

如何借VR之手,让展厅互动更精彩?

VR虚拟现实技术以其卓越的沉浸式体验为特点,引领用户踏入一个全新的虚拟世界,正因如此,它开始被广泛应用于展厅、商业等多个领域。那么,今天,让我们就来了解一下这种技术是如何为展厅带来精彩互动体验的吧!…

法国工程师数电练习题——有限状态机

1. 有限状态机 1.1 问题背景描述 给定的有限状态机由其状态图表示,具有两个输入E1和E2以及一个输出S。状态机为下图。请为以下输入序列绘制这个Moore机的时序图: 1) 在t50纳秒时,E1E211 2) 在t150纳秒时,E1E200 …

VMware17虚拟机安装Windows XP详解

简介 Windows XP是由Microsoft公司于2001年发布的操作系统。它是Windows家族中的一员,被广泛用于个人计算机和商业环境。Windows XP引入了一系列新功能和改进,包括更稳定的系统性能、更丰富的多媒体功能和更好的网络支持。 一、环境搭建 首先&#xf…

Llama 3-V: 比GPT4-V小100倍的SOTA

大模型技术论文不断,每个月总会新增上千篇。本专栏精选论文重点解读,主题还是围绕着行业实践和工程量产。若在某个环节出现卡点,可以回到大模型必备腔调重新阅读。而最新科技(Mamba,xLSTM,KAN)则提供了大模…

【VMware虚拟机中ubuntu系列】—— 在虚拟机中使用本机摄像头的详细教程与常见问题分析及解决

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言一、虚拟机调用本机摄像头(1) 启动VMware USB 服务(2) 连接本机摄像头(3) 测试摄像头的连接 二、安装usb驱动二、运行usb_cam.launch时出现select timeout的报错…

IDEA 学习之 疑难杂症系列

IDEA 学习之 疑难杂症系列 1. Mapstruct 编译空指针问题 1.1. 现象 NullPointerException at org.mapstruct.ap.internal.processor.DefaultVersionInformation.createManifest1.2. 原因 MapStruct 在 IDEA 2020.3 版本编译 NPE 问题 1.3. 解决办法 2. IDEA 学习之 编译内…