目录
- 写在前面
- 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: all
vars:
变量名1: 值
变量名2: 值
...
6.1.2 举例
#playbook
[root@manager playbook]# cat 05.pbvars.yaml
- hosts: front
vars:
my_var: "Hello, World!"
tasks:
- name: Use playbook-defined variable
debug:
msg: "{{ my_var }}"
- hosts: manager
vars:
my_var: "Hello, World!"
tasks:
- name: Use playbook-defined variable
debug:
msg: "{{ my_var }}"
# 运行
[root@manager playbook]# ansible-playbook 05.pbvars.yaml
PLAY [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中定义变量应用:
- 仅仅在当前play生效.
- 一般用来存放路径,用户名,ip地址,类似于之前使用的脚本.
- 注意引号使用.
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: front
vars_files: ./vars.yml
tasks:
- name: 显示内容
debug:
msg: "vars_file内的内容{{user}} {{dir}} {{file}}"
6.2.1.3 运行测试
[root@manager playbook]# ansible-playbook 06.vars-file.yaml
PLAY [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
提前创建好对应关系。
步骤:
- 在playbook文件同级目录下创建目录
group_vars
- 创建目录
主机组名/变量文件
,如下:
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: front
tasks:
- name: 显示内容
debug:
msg: "vars_file内的内容{{user}} {{nfs_dir}} {{nfs_server}}"
6.2.2.3 测试
[root@manager playbook]# ansible-playbook 07.group_vars.yaml
PLAY [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 date
shell: date +%F
register: result
#使用register变量
- name: debug
debug:
msg: "date的结果:{{result}}"
6.3.1 register使用
#编写playbook
[root@manager playbook]# cat 08.register.yaml
- hosts: front
tasks:
- name: get date
shell: date +%F
register: result #register: 变量名,接受上面的模块的结果
- name: debug
debug:
msg: "date的命令结果:{{result}}" #使用变量名即可
# 测试
[root@manager playbook]# ansible-playbook 08.register.yaml
PLAY [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: front
tasks:
- name: get date
shell: date +%F
register: result
- name: debug
debug:
msg: "date的命令结果:{{result.stdout}}" #变量名.stdout可以仅输出需要的内容stdout_lines
#测试
[root@manager playbook]# ansible-playbook 08.register.yaml
PLAY [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变量的实际案例
- 通过facts变量获取系统的基本信息
- 通过facts变量获取信息并进行判断
- 如果不需要可以进行关闭,加速剧本的运行(hosts行下一行添加
gather_facts: no
)
- hosts: front
gather_facts: no
tasks:
.....
- 批量修改系统/etc/motd文件(登陆时自动显示的文件)
- 输出主机名
- 内存大小
- ip
- 发行版本
- cpu数量
- 核心数量
#playbook编写
[root@manager playbook]# cat 10.change_moted.yaml
- hosts: front
tasks:
- name: template分发motd
template:
src: templates/motd.j2
dest: /etc/motd
backup: 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.yaml
PLAY [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 传输数据,复制文件的时候,文件中的变量会被解析和运行
.