1.Ansible变量概述详情
在Ansible中,变量是用于存储和引用值的标识符。它们可以在Playbooks、任务和模板中使用,使您能够动态地设置和使用值。变量在Ansible中非常重要,因为它们允许您编写灵活和可重用的配置。
以下是一些与Ansible变量相关的重要概念和用法:
变量定义:您可以在Playbooks、角色和任务中定义变量。变量可以是简单的标量值(如字符串或数字),也可以是复杂的数据结构(如列表、字典或对象)。
预定义变量:Ansible提供了一些预定义的变量,可以在Playbooks和模板中直接使用。这些变量包括ansible_hostname(主机名)、ansible_os_family(操作系统家族)和ansible_distribution(操作系统发行版)等。
变量的作用域:变量可以在不同的作用域中定义和使用。最常见的作用域是全局作用域和任务作用域。全局作用域中定义的变量在整个Playbook中都可用,而任务作用域中定义的变量仅在该任务中可用。
变量引用:在Playbooks和模板中,您可以使用{{ variable_name }}的语法引用变量。Ansible将在运行时替换变量引用为其实际值。
变量的优先级:当在多个地方定义相同名称的变量时,Ansible使用一套优先级规则来确定要使用的变量值。例如,任务级别的变量优先于角色级别的变量。
变量文件:您可以将变量定义保存在单独的变量文件中,并在Playbooks中使用vars_files关键字引入这些变量文件。这使得您可以将变量逻辑分离出来,使Playbooks更易于维护和管理。
动态变量:Ansible允许您使用Jinja2模板语言在运行时动态计算变量的值。这使得您可以根据主机属性、其他变量的值或其他条件来设置变量的值。
通过使用变量,您可以根据需要自定义和配置Ansible Playbooks和角色,使其更加灵活和可重用。变量使您能够编写通用的配置,并根据不同的环境和需求进行自定义。
2.Ansible变量优先级
在Ansible中,当多个位置都定义了相同名称的变量时,会使用一套优先级规则来确定要使用的变量值。以下是Ansible变量的优先级顺序:
命令行变量:通过在运行ansible-playbook命令时使用-e或–extra-vars选项指定的变量具有最高优先级。例如:ansible-playbook playbook.yml -e “my_var=value”
主机变量:您可以在Ansible的主机清单文件中为特定主机定义变量。这些变量仅适用于特定主机。
组变量:您可以在主机清单文件中为组定义变量。这些变量适用于该组中的所有主机。
主机和组变量文件:您可以在主机清单文件中引入变量文件,并为主机和组定义变量。这些变量在组和主机级别上具有较高的优先级。
角色变量:角色中定义的变量具有较低的优先级。您可以在角色的defaults目录中定义变量,这些变量将在角色中使用,但可以被其他更高优先级的变量覆盖。
Playbook变量:您可以在Playbook中定义变量,并将其应用于特定的任务或剧本。这些变量具有较低的优先级,并可以被其他更高优先级的变量覆盖。
系统环境变量:Ansible还可以使用系统环境变量作为变量。这些变量在Ansible中具有较低的优先级。
当存在多个变量定义时,Ansible将按照上述优先级顺序确定要使用的变量值。这使得您可以根据需要在不同的层次上定义和覆盖变量,以实现更灵活和可定制的配置。
变量使用
3.定义变量
在Ansible中,您可以使用vars
关键字来定义变量。变量可以在playbook中使用,以便在不同的任务和主机之间共享值。
有几种方法可以定义变量:
在playbook中定义变量:
- name: 定义变量
hosts: localhost
vars:
my_variable: value
tasks:
- name: 使用变量
debug:
var: my_variable
在单个任务中定义变量:
- name: 使用变量
hosts: localhost
tasks:
- name: 定义变量
set_fact:
my_variable: value
- name: 使用变量
debug:
var: my_variable
在主机组或主机的inventory文件中定义变量:
[my_group]
my_host ansible_host=192.168.1.100 my_variable=value
使用外部变量文件定义变量: 在playbook中使用vars_files
指定一个或多个外部变量文件,其中包含变量定义。
- name: 使用外部变量文件
hosts: localhost
vars_files:
- vars.yml
tasks:
- name: 使用变量
debug:
var: my_variable
这些只是定义变量的一些基本方法。您还可以使用动态变量、角色变量等更高级的功能来管理和使用变量
4.变量使用
playbook变量可以通过多种方式进行定义,最简单的方式就是在playbook的开头通过vars进行定义
剧本
[root@ansible /server/playbook]$ cat 05var.yml --- - hosts: al vars: - web_vars: nc - web_paly: nmap tasks: - name: install nmap yum: name: - "{{ web_vars }}" - "{{ web_paly }}" state: present
[root@ansible /server/playbook]$ ansible-playbook -C 05var.yml
也可以在playbook中使用vars_files指定文件作为变量文件,好处就是其他的playbook也可以调用
剧本
[root@ansible /server/playbook]$ cat 06var.yml --- - hosts: al vars_files: /server/playbook/vars.yml tasks: - name: install nmap yum: name: - "{{ web_vars }}" - "{{ web_paly }}" state: present
vars.yml文件
[root@ansible /server/playbook]$ cat vars.yml
web_vars: nc
web_paly: nmap
在inventory中定义变量,主机变量优先级高于主机组变量
剧本
[root@ansible /server/playbook]$ cat 06var.yml --- - hosts: al tasks: - name: install nmap yum: name: - "{{ web_vars }}" - "{{ web_paly }}" state: present
配置文件
[root@ansible /server/playbook]$ tail -3 /etc/ansible/hosts
[al:vars]
web_vars=nc
web_paly=nmap
ansible的项目目录中创建额外的两个变量目录,分别是host_vars和group_vars,需要主机host_vars优先级高于group_vars
创建目录
[root@ansible /server/playbook]$ mkdir -p group_vars/al
[root@ansible /server/playbook]$ cat group_vars/al/vars.yml
web_vars: nc
web_paly: nmap
剧本
[root@ansible /server/playbook]$ cat 06var.yml --- - hosts: al tasks: - name: install nmap yum: name: - "{{ web_vars }}" - "{{ web_paly }}" state: present
[root@ansible /server/playbook]$ ansible-playbook 06var.yml
5.变量注册
在Ansible中,您可以使用变量注册来捕获任务执行的结果,并将其存储到一个变量中以供后续使用。变量注册使用`register`关键字来指定要存储结果的变量名。
以下是一个使用变量注册的示例:
- name: 示例任务
hosts: my_group
tasks:
- name: 运行命令并注册结果
command: echo "Hello, World!"
register: result
- name: 打印结果
debug:
var: result.stdout
在上面的示例中,我们使用`command`模块运行一个命令,并将其结果注册到名为`result`的变量中。
在后续的任务中,我们使用`debug`模块打印变量`result.stdout`的值。`result.stdout`表示命令的标准输出。
通过变量注册,您可以捕获任务的执行结果,并在后续的任务中使用。这对于需要根据任务结果进行条件判断或执行其他操作的情况非常有用。
除了`command`模块,您还可以在其他模块中使用变量注册。例如,在`shell`模块中运行Shell命令,或在`fetch`模块中获取远程文件的内容等。
请注意,变量注册的结果是一个字典,其中包含了任务执行的各种信息,如标准输出、标准错误、返回码等。您可以根据需要访问这些信息。在上面的示例中,我们使用`result.stdout`来访问命令的标准输出。
var、msg区别
在Ansible的`debug`模块中,`var`和`msg`参数用于打印变量的值,但它们有一些区别。
`var`参数用于打印变量的值,它会直接打印变量的值,不会添加任何额外的文本。例如:
- name: 打印变量 debug: var: my_variable
在上面的示例中,`my_variable`是要打印的变量名称,使用`var`参数可以直接打印变量的值。
– `msg`参数用于打印消息,并可以在消息中引用变量的值。它可以添加额外的文本,并使用`{{ }}`语法来引用变量的值。例如:
- name: 打印变量 debug: msg: "变量的值是 {{ my_variable }}"
在上面的示例中,使用`msg`参数可以在打印时添加一些额外的文本,并使用`{{ }}`语法来引用变量的值。
总结来说,`var`参数用于直接打印变量的值,而`msg`参数用于打印消息并引用变量的值。您可以根据需要选择使用`var`或`msg`参数来打印变量的值。如果只需要打印变量的值,那么使用`var`参数更简洁。如果需要在打印时添加一些额外的文本,并引用变量的值,那么使用`msg`参数更灵活。
剧本
[root@ansible /server/playbook]$ cat 07register.yml --- - hosts: al tasks: - name: ip addr shell: ip a
[root@ansible /server/playbook]$ ansible-playbook 07register.yml -C PLAY [al] ********************************************************************************************************************* TASK [Gathering Facts] ******************************************************************************************************** ok: [172.16.1.78] TASK [ip addr] **************************************************************************************************************** skipping: [172.16.1.78] PLAY RECAP ******************************************************************************************************************** 172.16.1.78 : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
添加register
[root@ansible /server/playbook]$ cat 07register.yml --- - hosts: al tasks: - name: ip addr shell: hostname -I register: ip_addr - name: echo debug: msg: "you ip address is {{ ip_addr }}"
[root@ansible /server/playbook]$ ansible-playbook 07register.yml PLAY [al] ********************************************************************************************************************* TASK [Gathering Facts] ******************************************************************************************************** ok: [172.16.1.78] TASK [ip addr] **************************************************************************************************************** changed: [172.16.1.78] TASK [echo] ******************************************************************************************************************* ok: [172.16.1.78] => { "msg": "you ip address is {'stderr_lines': [], u'changed': True, u'end': u'2023-08-07 11:28:13.526129', 'failed': False, u'stdout': u'10.0.0.78 172.16.1.78 ', u'cmd': u'hostname -I', u'rc': 0, u'start': u'2023-08-07 11:28:13.518866', u'stderr': u'', u'delta': u'0:00:00.007263', 'stdout_lines': [u'10.0.0.78 172.16.1.78 ']}" } PLAY RECAP ******************************************************************************************************************** 172.16.1.78 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 {'stderr_lines': [], u'changed': True, u'end': u'2023-08-07 11:28:13.526129', 'failed': False, u 'stdout': u'10.0.0.78 172.16.1.78 ', u'cmd': u'hostname -I', u 'rc': 0, u'start': u'2023-08-07 11:28:13.518866', u 'stderr': u'', u'delta': u'0:00:00.007263', 'stdout_lines': [u'10.0.0.78 172.16.1.78 ']}" }
变量叫做ip_addr
ip_addr.stdout_lines:取出ip
ip_addr.rc:返回值 return code $?
ip_addr.stdout:标准输出, 屏幕上面的输出
ip_addr.stderr:标准错误输出,错误信息
6.facts变量
Ansible facts变量是一组关于远程主机的事实信息,包括主机名、操作系统、网络接口、内存、CPU等。这些信息在Ansible的执行过程中自动收集并存储在`ansible_facts`变量中。
以下是一些常用的Ansible facts变量:
`ansible_facts[‘ansible_hostname’]`:远程主机的主机名。
`ansible_facts[‘ansible_default_ipv4’]`:远程主机的默认IPv4地址信息。
`ansible_facts[‘ansible_default_ipv6’]`:远程主机的默认IPv6地址信息。
`ansible_facts[‘ansible_distribution’]`:远程主机的操作系统发行版名称。
`ansible_facts[‘ansible_distribution_version’]`:远程主机的操作系统发行版版本。
`ansible_facts[‘ansible_distribution_release’]`:远程主机的操作系统发行版发布号。
`ansible_facts[‘ansible_architecture’]`:远程主机的架构(比如x86_64)。
`ansible_facts[‘ansible_memtotal_mb’]`:远程主机的总内存大小(以MB为单位)。
`ansible_facts[‘ansible_processor_vcpus’]`:远程主机的CPU核心数。
`ansible_facts[‘ansible_interfaces’]`:远程主机的网络接口列表。
可以使用`debug`模块来输出这些facts变量,例如:
- name: 输出远程主机信息 debug: msg: "主机名: {{ ansible_facts['ansible_hostname'] }}, IP地址: {{ ansible_facts['ansible_default_ipv4']['address'] }}, 操作系统: {{ ansible_facts['ansible_distribution'] }}"
在这个示例中,使用了`ansible_facts`变量来输出远程主机的主机名、IP地址和操作系统信息。可以根据需要引用其他的facts变量来输出更多的信息。
可以通过`ansible -m setup <hostname>`命令来查看远程主机的所有facts变量。也可以通过`ansible_facts`变量在Playbook中使用这些信息。
facts使用场景
Ansible facts变量可以在Ansible的Playbook中使用,用于根据远程主机的事实信息来执行不同的任务或决策。以下是一些常见的使用场景:
条件判断:可以使用facts变量来判断远程主机的操作系统类型、版本、架构等信息,从而根据不同的条件执行不同的任务或配置。
主机过滤:可以使用facts变量来过滤主机,只对特定的操作系统、架构或其他特征的主机执行任务。
变量赋值:可以使用facts变量来获取远程主机的信息,并将其赋值给自定义变量,以便在后续的任务中使用。
模板渲染:可以使用facts变量来填充模板文件,生成基于远程主机信息的配置文件。
输出报告:可以使用facts变量来生成关于远程主机的报告,包括主机名、操作系统、内存、CPU等信息。
自动化决策:可以使用facts变量来自动决策,比如根据主机的内存大小选择合适的应用部署方案。
需要注意的是,Ansible会在执行Playbook的过程中自动收集远程主机的facts信息,无需额外的配置。可以通过`ansible_facts`变量来访问这些信息。可以使用`setup`模块或`ansible -m setup <hostname>`命令来查看远程主机的所有facts变量。
在Playbook中使用facts变量时,可以使用`when`条件语句、`inventory_hostname`变量、`ansible_facts`变量等来根据需要进行判断和引用。
显示所有 ansible facts
[root@ansible /server/playbook]$ ansible 172.16.1.78 -m setup 172.16.1.78 | SUCCESS => { "ansible_facts": { "ansible_all_ipv4_addresses": [ "172.16.1.78", "10.0.0.78" ], "ansible_all_ipv6_addresses": [ "fe80::250:56ff:fe24:6451", "fe80::250:56ff:fe37:3f8e" ], "ansible_apparmor": { "status": "disabled" }, "ansible_architecture": "x86_64", "ansible_bios_date": "07/22/2020", "ansible_bios_version": "6.00", "ansible_cmdline": { "BOOT_IMAGE": "/vmlinuz-3.10.0-1127.el7.x86_64", "LANG": "en_US.UTF-8", "biosdevname": "0", "crashkernel": "auto", "net.ifnames": "0", "quiet": true, "rd.lvm.lv": "centos/swap", "rhgb": true, "ro": true, "root": "/dev/mapper/centos-root", "spectre_v2": "retpoline" }, "ansible_date_time": { "date": "2023-08-08", "day": "08", "epoch": "1691459623", "hour": "09", "iso8601": "2023-08-08T01:53:43Z", "iso8601_basic": "20230808T095343763132", "iso8601_basic_short": "20230808T095343", "iso8601_micro": "2023-08-08T01:53:43.763132Z", "minute": "53", "month": "08", "second": "43", "time": "09:53:43", "tz": "CST", "tz_offset": "+0800", "weekday": "Tuesday", "weekday_number": "2", "weeknumber": "32", "year": "2023" }, "ansible_default_ipv4": { "address": "10.0.0.78", "alias": "eth0", "broadcast": "10.0.0.255", "gateway": "10.0.0.2", "interface": "eth0", "macaddress": "00:50:56:37:3f:8e", "mtu": 1500, "netmask": "255.255.255.0", "network": "10.0.0.0", "type": "ether" }, "ansible_default_ipv6": {}, "ansible_device_links": { "ids": { "dm-0": [ "dm-name-centos-root", "dm-uuid-LVM-HCWQlQaQFPWs1ZP4DVzZQfW8WAdjrLeRsaQOYbw38OrY1dvyYpNu60NRH0jVwKKJ" ], "dm-1": [ "dm-name-centos-swap", "dm-uuid-LVM-HCWQlQaQFPWs1ZP4DVzZQfW8WAdjrLeRZSfFcq2KXnOFcZjbCGb4X2A5eCicqnTO" ], "sda2": [ "lvm-pv-uuid-cvNneq-NfnO-kCvx-3FVD-vYST-cIAw-fvUcXc" ], "sr0": [ "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001" ] }, "labels": { "sr0": [ "CentOS\\x207\\x20x86_64" ] }, "masters": { "sda2": [ "dm-0", "dm-1" ] }, "uuids": { "dm-0": [ "1cfd0a4f-a5e3-40ba-bbfe-289e8fd0b694" ], "dm-1": [ "aaa043bb-aa90-4fd6-9cc8-f7948a830954" ], "sda1": [ "17e70c68-1201-4286-a802-61b85fa09c5b" ], "sr0": [ "2020-04-22-00-54-00-00" ] } }, "ansible_devices": { "dm-0": { "holders": [], "host": "", "links": { "ids": [ "dm-name-centos-root", "dm-uuid-LVM-HCWQlQaQFPWs1ZP4DVzZQfW8WAdjrLeRsaQOYbw38OrY1dvyYpNu60NRH0jVwKKJ" ], "labels": [], "masters": [], "uuids": [ "1cfd0a4f-a5e3-40ba-bbfe-289e8fd0b694" ] }, "model": null, "partitions": {}, "removable": "0", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "", "sectors": "98549760", "sectorsize": "512", "size": "46.99 GB", "support_discard": "0", "vendor": null, "virtual": 1 }, "dm-1": { "holders": [], "host": "", "links": { "ids": [ "dm-name-centos-swap", "dm-uuid-LVM-HCWQlQaQFPWs1ZP4DVzZQfW8WAdjrLeRZSfFcq2KXnOFcZjbCGb4X2A5eCicqnTO" ], "labels": [], "masters": [], "uuids": [ "aaa043bb-aa90-4fd6-9cc8-f7948a830954" ] }, "model": null, "partitions": {}, "removable": "0", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "", "sectors": "4194304", "sectorsize": "512", "size": "2.00 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": [ "17e70c68-1201-4286-a802-61b85fa09c5b" ] }, "sectors": "2097152", "sectorsize": 512, "size": "1.00 GB", "start": "2048", "uuid": "17e70c68-1201-4286-a802-61b85fa09c5b" }, "sda2": { "holders": [ "centos-root", "centos-swap" ], "links": { "ids": [ "lvm-pv-uuid-cvNneq-NfnO-kCvx-3FVD-vYST-cIAw-fvUcXc" ], "labels": [], "masters": [ "dm-0", "dm-1" ], "uuids": [] }, "sectors": "102758400", "sectorsize": 512, "size": "49.00 GB", "start": "2099200", "uuid": null } }, "removable": "0", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "deadline", "sectors": "104857600", "sectorsize": "512", "size": "50.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": [ "CentOS\\x207\\x20x86_64" ], "masters": [], "uuids": [ "2020-04-22-00-54-00-00" ] }, "model": "VMware IDE CDR10", "partitions": {}, "removable": "1", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "deadline", "sectors": "9338880", "sectorsize": "2048", "size": "4.45 GB", "support_discard": "0", "vendor": "NECVMWar", "virtual": 1 } }, "ansible_distribution": "CentOS", "ansible_distribution_file_parsed": true, "ansible_distribution_file_path": "/etc/redhat-release", "ansible_distribution_file_variety": "RedHat", "ansible_distribution_major_version": "7", "ansible_distribution_release": "Core", "ansible_distribution_version": "7.8", "ansible_dns": { "nameservers": [ "223.5.5.5" ] }, "ansible_domain": "", "ansible_effective_group_id": 0, "ansible_effective_user_id": 0, "ansible_env": { "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:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=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:*.jpg=01;35:*.jpeg=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:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=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:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:", "MAIL": "/var/mail/root", "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", "PWD": "/root", "SHELL": "/bin/bash", "SHLVL": "2", "SSH_CLIENT": "172.16.1.5 33896 22", "SSH_CONNECTION": "172.16.1.5 33896 172.16.1.78 22", "SSH_TTY": "/dev/pts/1", "TERM": "linux", "USER": "root", "XDG_RUNTIME_DIR": "/run/user/0", "XDG_SESSION_ID": "5310", "_": "/usr/bin/python" }, "ansible_eth0": { "active": true, "device": "eth0", "features": { "busy_poll": "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_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", "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_fcoe_segmentation": "off [fixed]", "tx_gre_csum_segmentation": "off [fixed]", "tx_gre_segmentation": "off [fixed]", "tx_gso_partial": "off [fixed]", "tx_gso_robust": "off [fixed]", "tx_ipip_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_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "off [fixed]", "tx_tcp_ecn_segmentation": "off [fixed]", "tx_tcp_mangleid_segmentation": "off", "tx_tcp_segmentation": "on", "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]", "udp_fragmentation_offload": "off [fixed]", "vlan_challenged": "off [fixed]" }, "hw_timestamp_filters": [], "ipv4": { "address": "10.0.0.78", "broadcast": "10.0.0.255", "netmask": "255.255.255.0", "network": "10.0.0.0" }, "ipv6": [ { "address": "fe80::250:56ff:fe37:3f8e", "prefix": "64", "scope": "link" } ], "macaddress": "00:50:56:37:3f:8e", "module": "e1000", "mtu": 1500, "pciid": "0000:02:01.0", "promisc": false, "speed": 1000, "timestamping": [ "tx_software", "rx_software", "software" ], "type": "ether" }, "ansible_eth1": { "active": true, "device": "eth1", "features": { "busy_poll": "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_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", "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_fcoe_segmentation": "off [fixed]", "tx_gre_csum_segmentation": "off [fixed]", "tx_gre_segmentation": "off [fixed]", "tx_gso_partial": "off [fixed]", "tx_gso_robust": "off [fixed]", "tx_ipip_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_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "off [fixed]", "tx_tcp_ecn_segmentation": "off [fixed]", "tx_tcp_mangleid_segmentation": "off", "tx_tcp_segmentation": "on", "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]", "udp_fragmentation_offload": "off [fixed]", "vlan_challenged": "off [fixed]" }, "hw_timestamp_filters": [], "ipv4": { "address": "172.16.1.78", "broadcast": "172.16.1.255", "netmask": "255.255.255.0", "network": "172.16.1.0" }, "ipv6": [ { "address": "fe80::250:56ff:fe24:6451", "prefix": "64", "scope": "link" } ], "macaddress": "00:50:56:24:64:51", "module": "e1000", "mtu": 1500, "pciid": "0000:02:02.0", "promisc": false, "speed": 1000, "timestamping": [ "tx_software", "rx_software", "software" ], "type": "ether" }, "ansible_fibre_channel_wwn": [], "ansible_fips": false, "ansible_form_factor": "Other", "ansible_fqdn": "all", "ansible_hostname": "all", "ansible_hostnqn": "", "ansible_interfaces": [ "lo", "eth1", "eth0" ], "ansible_is_chroot": false, "ansible_iscsi_iqn": "", "ansible_kernel": "3.10.0-1127.el7.x86_64", "ansible_kernel_version": "#1 SMP Tue Mar 31 23:36:51 UTC 2020", "ansible_lo": { "active": true, "device": "lo", "features": { "busy_poll": "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_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", "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_fcoe_segmentation": "off [fixed]", "tx_gre_csum_segmentation": "off [fixed]", "tx_gre_segmentation": "off [fixed]", "tx_gso_partial": "off [fixed]", "tx_gso_robust": "off [fixed]", "tx_ipip_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_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "on", "tx_tcp_ecn_segmentation": "on", "tx_tcp_mangleid_segmentation": "on", "tx_tcp_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]", "udp_fragmentation_offload": "on", "vlan_challenged": "on [fixed]" }, "hw_timestamp_filters": [], "ipv4": { "address": "127.0.0.1", "broadcast": "", "netmask": "255.0.0.0", "network": "127.0.0.0" }, "ipv6": [ { "address": "::1", "prefix": "128", "scope": "host" } ], "mtu": 65536, "promisc": false, "timestamping": [ "rx_software", "software" ], "type": "loopback" }, "ansible_local": {}, "ansible_lsb": {}, "ansible_lvm": { "lvs": { "root": { "size_g": "46.99", "vg": "centos" }, "swap": { "size_g": "2.00", "vg": "centos" } }, "pvs": { "/dev/sda2": { "free_g": "0.00", "size_g": "49.00", "vg": "centos" } }, "vgs": { "centos": { "free_g": "0.00", "num_lvs": "2", "num_pvs": "1", "size_g": "49.00" } } }, "ansible_machine": "x86_64", "ansible_machine_id": "5e918c2ff6934327a06c0471021125c2", "ansible_memfree_mb": 1491, "ansible_memory_mb": { "nocache": { "free": 1649, "used": 170 }, "real": { "free": 1491, "total": 1819, "used": 328 }, "swap": { "cached": 0, "free": 2047, "total": 2047, "used": 0 } }, "ansible_memtotal_mb": 1819, "ansible_mounts": [ { "block_available": 184206, "block_size": 262144, "block_total": 192387, "block_used": 8181, "device": "172.16.1.78:/data-nfs", "fstype": "nfs4", "inode_available": 24574787, "inode_total": 24637440, "inode_used": 62653, "mount": "/tmp", "options": "rw,relatime,vers=4.1,rsize=262144,wsize=262144,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=172.16.1.78,local_lock=none,addr=172.16.1.78", "size_available": 48288497664, "size_total": 50433097728, "uuid": "N/A" }, { "block_available": 221106, "block_size": 4096, "block_total": 259584, "block_used": 38478, "device": "/dev/sda1", "fstype": "xfs", "inode_available": 523961, "inode_total": 524288, "inode_used": 327, "mount": "/boot", "options": "rw,relatime,attr2,inode64,noquota", "size_available": 905650176, "size_total": 1063256064, "uuid": "17e70c68-1201-4286-a802-61b85fa09c5b" }, { "block_available": 184206, "block_size": 262144, "block_total": 192387, "block_used": 8181, "device": "172.16.1.78:/data-nfs", "fstype": "nfs4", "inode_available": 24574787, "inode_total": 24637440, "inode_used": 62653, "mount": "/mnt", "options": "rw,relatime,vers=4.1,rsize=262144,wsize=262144,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=172.16.1.78,local_lock=none,addr=172.16.1.78", "size_available": 48288497664, "size_total": 50433097728, "uuid": "N/A" }, { "block_available": 11789163, "block_size": 4096, "block_total": 12312705, "block_used": 523542, "device": "/dev/mapper/centos-root", "fstype": "xfs", "inode_available": 24574787, "inode_total": 24637440, "inode_used": 62653, "mount": "/", "options": "rw,relatime,attr2,inode64,noquota", "size_available": 48288411648, "size_total": 50432839680, "uuid": "1cfd0a4f-a5e3-40ba-bbfe-289e8fd0b694" } ], "ansible_nodename": "all", "ansible_os_family": "RedHat", "ansible_pkg_mgr": "yum", "ansible_proc_cmdline": { "BOOT_IMAGE": "/vmlinuz-3.10.0-1127.el7.x86_64", "LANG": "en_US.UTF-8", "biosdevname": "0", "crashkernel": "auto", "net.ifnames": "0", "quiet": true, "rd.lvm.lv": [ "centos/root", "centos/swap" ], "rhgb": true, "ro": true, "root": "/dev/mapper/centos-root", "spectre_v2": "retpoline" }, "ansible_processor": [ "0", "GenuineIntel", "Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz" ], "ansible_processor_cores": 1, "ansible_processor_count": 1, "ansible_processor_threads_per_core": 1, "ansible_processor_vcpus": 1, "ansible_product_name": "VMware Virtual Platform", "ansible_product_serial": "VMware-56 4d f8 05 24 e2 2a e3-5d 3d ce 11 97 ce b7 db", "ansible_product_uuid": "05F84D56-E224-E32A-5D3D-CE1197CEB7DB", "ansible_product_version": "None", "ansible_python": { "executable": "/usr/bin/python", "has_sslcontext": true, "type": "CPython", "version": { "major": 2, "micro": 5, "minor": 7, "releaselevel": "final", "serial": 0 }, "version_info": [ 2, 7, 5, "final", 0 ] }, "ansible_python_version": "2.7.5", "ansible_real_group_id": 0, "ansible_real_user_id": 0, "ansible_selinux": { "status": "disabled" }, "ansible_selinux_python_present": true, "ansible_service_mgr": "systemd", "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEpvyOBL2arP8fp+UopqGXcbJu8r5OWjmccIS1hMY6S73RKgFXtcao+Ydv/rBj8kSa/2FYKwjwY9ZDE+KfTKd3k=", "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIETLhr2yJfkwHLo0TbmgbgjZgUVOilVImTeg5ME3rNki", "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDmsFpRpCGSkswjpYGZAvCFxj/hZJ2X6k8IAqWZw9gBdsfQBFh7fWoRPtFGKTu7+OHCO9+0JRcze+D81zP5N8tDHTi8m3HsJ9RSud83rrFSgxh9GLmNcjuRyPeH5rWmbJ6+BEorZFP4DZ53M87A7iu+D3xB8emt9nckd7Er5p0GDsbqR9pl2IczypQ3Pba5pAyiAdjG1HTBErpYFwq7IxopFu7QUJwxL7qj57axUU7YR9vXLQgTKyJzzabKrwYYdWjGT8QnUnZ1fbzwTPfvryrB/pOTBLl+qk1crTwshulMIhP5mdApYXYcjUmLv1Rwdfu012vGKbYMt7d0pwcCqS5n", "ansible_swapfree_mb": 2047, "ansible_swaptotal_mb": 2047, "ansible_system": "Linux", "ansible_system_capabilities": [ "cap_chown", "cap_dac_override", "cap_dac_read_search", "cap_fowner", "cap_fsetid", "cap_kill", "cap_setgid", "cap_setuid", "cap_setpcap", "cap_linux_immutable", "cap_net_bind_service", "cap_net_broadcast", "cap_net_admin", "cap_net_raw", "cap_ipc_lock", "cap_ipc_owner", "cap_sys_module", "cap_sys_rawio", "cap_sys_chroot", "cap_sys_ptrace", "cap_sys_pacct", "cap_sys_admin", "cap_sys_boot", "cap_sys_nice", "cap_sys_resource", "cap_sys_time", "cap_sys_tty_config", "cap_mknod", "cap_lease", "cap_audit_write", "cap_audit_control", "cap_setfcap", "cap_mac_override", "cap_mac_admin", "cap_syslog", "35", "36+ep" ], "ansible_system_capabilities_enforced": "True", "ansible_system_vendor": "VMware, Inc.", "ansible_uptime_seconds": 515022, "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_type": "VMware", "discovered_interpreter_python": "/usr/bin/python", "gather_subset": [ "all" ], "module_setup": true }, "changed": false }
通过filter进行过滤 显示我们索要的facts
[root@ansible /server/playbook]$ ansible 172.16.1.78 -m setup -a 'filter="*eth1*"' 172.16.1.78 | SUCCESS => { "ansible_facts": { "ansible_eth1": { "active": true, "device": "eth1", "features": { "busy_poll": "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_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", "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_fcoe_segmentation": "off [fixed]", "tx_gre_csum_segmentation": "off [fixed]", "tx_gre_segmentation": "off [fixed]", "tx_gso_partial": "off [fixed]", "tx_gso_robust": "off [fixed]", "tx_ipip_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_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "off [fixed]", "tx_tcp_ecn_segmentation": "off [fixed]", "tx_tcp_mangleid_segmentation": "off", "tx_tcp_segmentation": "on", "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]", "udp_fragmentation_offload": "off [fixed]", "vlan_challenged": "off [fixed]" }, "hw_timestamp_filters": [], "ipv4": { "address": "172.16.1.78", "broadcast": "172.16.1.255", "netmask": "255.255.255.0", "network": "172.16.1.0" }, "ipv6": [ { "address": "fe80::250:56ff:fe24:6451", "prefix": "64", "scope": "link" } ], "macaddress": "00:50:56:24:64:51", "module": "e1000", "mtu": 1500, "pciid": "0000:02:02.0", "promisc": false, "speed": 1000, "timestamping": [ "tx_software", "rx_software", "software" ], "type": "ether" }, "discovered_interpreter_python": "/usr/bin/python" }, "changed": false }
facts基本用法,获取被控端的主机名与IP地址
剧本
[root@ansible /server/playbook]$ cat 08debug.yml --- - hosts: al tasks: - name: echo debug: msg: - "name {{ ansible_hostname }}" - "所有的ip地址 {{ ansible_all_ipv4_addresses }}" - "默认的ip地址 {{ ansible_default_ipv4.address }}" - "you interface is {{ ansible_default_ipv4.interface }}" - "time is {{ ansible_date_time.date }}" - "mem total is {{ ansible_memtotal_mb }}" - "you system is {{ ansible_distribution }} version is {{ ansible_distribution_version }}"
[root@ansible /server/playbook]$ ansible-playbook 08debug.yml PLAY [al] ********************************************************************************************************************* TASK [Gathering Facts] ******************************************************************************************************** ok: [172.16.1.78] TASK [echo] ******************************************************************************************************************* ok: [172.16.1.78] => { "msg": [ "name all ", "所有的ip地址 [u'172.16.1.78', u'10.0.0.78']", "默认的ip地址 10.0.0.78", "you interface is eth0", "time is 2023-08-08", "mem total is 1819", "you system is CentOS version is 7.8" ] } PLAY RECAP ******************************************************************************************************************** 172.16.1.78 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
facts开启后会影响Ansible主机的性能,如果没有采集被控端主机需求可选择关闭
剧本
[root@ansible /server/playbook]$ cat 08debug.yml --- - hosts: al gather_facts: no tasks: - name: echo debug: msg: - "name {{ ansible_hostname }} " - "所有的ip地址 {{ ansible_all_ipv4_addresses }}" - "默认的ip地址 {{ ansible_default_ipv4.address }}" - "you interface is {{ ansible_default_ipv4.interface }}" - "time is {{ ansible_date_time.date }}" - "mem total is {{ ansible_memtotal_mb }}" - "you system is {{ ansible_distribution }} version is {{ ansible_distribution_version }}" [root@ansible /server/playbook]$ ansible-playbook 08debug.yml PLAY [al] ********************************************************************************************************************* TASK [echo] ******************************************************************************************************************* fatal: [172.16.1.78]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible_hostname' is undefined\n\nThe error appears to be in '/server/playbook/08debug.yml': line 5, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - name: echo\n ^ here\n"} PLAY RECAP ******************************************************************************************************************** 172.16.1.78 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
使用facts根据不同的内存生成不同Memcached配置文件
剧本
[root@ansible /server/playbook]$ cat 09memcached.yml --- - hosts: web tasks: - name: Install Memcached yum: name: memcached state: present - name: Configure Memcached template: src: /server/playbook/memcached.j2 dest: /etc/sysconfig/memcached - name: Start Memcached service: name: memcached enabled: yes
配置文件
[root@ansible /server/playbook]$ cat memcached.j2 PORT="11211" USER="memcached" MAXCONN="1024" CACHESIZE="{{ ansible_memtotal_mb //2 }}" OPTIONS=""