Ansible playbook之变量引用

news/2024/10/18 0:01:50/

1.Ansible facts

        facts是一个用于采集被管理机器设备信息的一个组件,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。

[root@ansible01 ~]# ansible 11.0.1.19 -m setup
11.0.1.19 | SUCCESS => {"ansible_facts": {"ansible_all_ipv4_addresses": ["11.0.1.19"], "ansible_all_ipv6_addresses": ["fe80::20c:29ff:feaf:86c8"], "ansible_apparmor": {"status": "disabled"}, "ansible_architecture": "x86_64", "ansible_bios_date": "11/12/2020", "ansible_bios_version": "6.00", "ansible_cmdline": {"BOOT_IMAGE": "/vmlinuz-3.10.0-327.el7.x86_64", "LANG": "en_US.UTF-8", "crashkernel": "auto", "quiet": true, "rhgb": true, "ro": true, "root": "UUID=c058400b-3be7-4902-ba95-8c08abf428ba"}, "ansible_date_time": {"date": "2024-04-21", "day": "21", "epoch": "1713751417", "hour": "19", "iso8601": "2024-04-22T02:03:37Z", "iso8601_basic": "20240421T190337661048", "iso8601_basic_short": "20240421T190337", "iso8601_micro": "2024-04-22T02:03:37.661048Z", "minute": "03", "month": "04", "second": "37", "time": "19:03:37", "tz": "PDT", "tz_offset": "-0700", "weekday": "星期日", "weekday_number": "0", "weeknumber": "16", "year": "2024"......

运行facter模块来查看facter信息:

[root@ansible01 ~]# ansible 11.0.1.19 -m facter
11.0.1.19 | FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "cmd": "--json", "msg": "[Errno 2] 没有那个文件或目录", "rc": 2
}

报错是因为被管节点没有安装facter的包,我们先去被管节点安装在执行ansible 11.0.1.19 -m facter:

#1.在11.0.1.19被管控机上安装facter
[root@ansible02 ~]# yum install -y facter.x86_64
Loaded plugins: langpacks, product-id, search-disabled-repos, subscription-manager
epel                                                                                                                                                                                                              | 4.7 kB  00:00:00     
rhel-7-server-rpms                                                                                                                                                                                                | 3.5 kB  00:00:00     
(1/4): epel/x86_64/updateinfo                                                                                                                                                                                     | 1.0 MB  00:00:01     
(2/4): epel/x86_64/primary_db                                                                                                                                                                                     | 7.0 MB  00:00:06     
(3/4): rhel-7-server-rpms/7Server/x86_64/updateinfo                                                                                                                                                               | 4.3 MB  00:00:16     
(4/4): rhel-7-server-rpms/7Server/x86_64/primary_db                                                                                                                                                               |  95 MB  00:01:39     
Resolving Dependencies
--> Running transaction check
---> Package facter.x86_64 0:2.4.1-1.el7 will be installed
--> Processing Dependency: /usr/bin/ruby for package: facter-2.4.1-1.el7.x86_64
--> Running transaction check
---> Package ruby.x86_64 0:2.0.0.648-39.el7_9 will be installed
--> Processing Dependency: ruby-libs(x86-64) = 2.0.0.648-39.el7_9 for package: ruby-2.0.0.648-39.el7_9.x86_64
--> Processing Dependency: ruby(rubygems) >= 2.0.14.1 for package: ruby-2.0.0.648-39.el7_9.x86_64
--> Processing Dependency: rubygem(bigdecimal) >= 1.2.0 for package: ruby-2.0.0.648-39.el7_9.x86_64
--> Processing Dependency: libruby.so.2.0()(64bit) for package: ruby-2.0.0.648-39.el7_9.x86_64
--> Running transaction check
---> Package ruby-libs.x86_64 0:2.0.0.648-39.el7_9 will be installed
---> Package rubygem-bigdecimal.x86_64 0:1.2.0-39.el7_9 will be installed
---> Package rubygems.noarch 0:2.0.14.1-39.el7_9 will be installed
--> Processing Dependency: rubygem(io-console) >= 0.4.2 for package: rubygems-2.0.14.1-39.el7_9.noarch
--> Processing Dependency: rubygem(psych) >= 2.0.0 for package: rubygems-2.0.14.1-39.el7_9.noarch
--> Processing Dependency: rubygem(rdoc) >= 4.0.0 for package: rubygems-2.0.14.1-39.el7_9.noarch
--> Running transaction check
---> Package rubygem-io-console.x86_64 0:0.4.2-39.el7_9 will be installed
---> Package rubygem-psych.x86_64 0:2.0.0-39.el7_9 will be installed
---> Package rubygem-rdoc.noarch 0:4.0.0-39.el7_9 will be installed
--> Processing Dependency: ruby(irb) = 2.0.0.648 for package: rubygem-rdoc-4.0.0-39.el7_9.noarch
--> Processing Dependency: rubygem(json) >= 1.7.7 for package: rubygem-rdoc-4.0.0-39.el7_9.noarch
--> Running transaction check
---> Package ruby-irb.noarch 0:2.0.0.648-39.el7_9 will be installed
---> Package rubygem-json.x86_64 0:1.7.7-39.el7_9 will be installed
--> Finished Dependency Resolution
......
Installed:facter.x86_64 0:2.4.1-1.el7                                                                                                                                                                                                            Dependency Installed:ruby.x86_64 0:2.0.0.648-39.el7_9           ruby-irb.noarch 0:2.0.0.648-39.el7_9        ruby-libs.x86_64 0:2.0.0.648-39.el7_9       rubygem-bigdecimal.x86_64 0:1.2.0-39.el7_9       rubygem-io-console.x86_64 0:0.4.2-39.el7_9      rubygem-json.x86_64 0:1.7.7-39.el7_9       rubygem-psych.x86_64 0:2.0.0-39.el7_9       rubygem-rdoc.noarch 0:4.0.0-39.el7_9        rubygems.noarch 0:2.0.14.1-39.el7_9             Complete!
#2.在11.0.1.18上执行
[root@ansible01 ~]# ansible 11.0.1.19 -m facter
11.0.1.19 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "architecture": "x86_64", "bios_release_date": "11/12/2020", "bios_vendor": "Phoenix Technologies LTD", "bios_version": "6.00", "blockdevice_sda_model": "VMware Virtual S", "blockdevice_sda_size": 21474836480, "blockdevice_sda_vendor": "VMware,", "blockdevice_sr0_model": "VMware SATA CD00", "blockdevice_sr0_size": 47063040, "blockdevice_sr0_vendor": "NECVMWar", "blockdevice_sr1_model": "VMware SATA CD01", "blockdevice_sr1_size": 4043309056, "blockdevice_sr1_vendor": "NECVMWar", "blockdevices": "sda,sr0,sr1", "boardmanufacturer": "Intel Corporation", "boardproductname": "440BX Desktop Reference Platform", "boardserialnumber": "None", "changed": false, "facterversion": "2.4.1", "filesystems": "xfs", "fqdn": "ansible02", "gid": "root", "hardwareisa": "x86_64", "hardwaremodel": "x86_64", "hostname": "ansible02", "id": "root", "interfaces": "eno16777736,lo", "ipaddress": "11.0.1.19", "ipaddress_eno16777736": "11.0.1.19", "ipaddress_lo": "127.0.0.1", "is_virtual": true, "kernel": "Linux", "kernelmajversion": "3.10", "kernelrelease": "3.10.0-327.el7.x86_64", "kernelversion": "3.10.0", "macaddress": "00:0c:29:af:86:c8", "macaddress_eno16777736": "00:0c:29:af:86:c8", "manufacturer": "VMware, Inc.", "memoryfree": "1.39 GB", "memoryfree_mb": "1424.84", "memorysize": "1.78 GB", "memorysize_mb": "1824.89", "mtu_eno16777736": 1500, "mtu_lo": 65536, "netmask": "255.255.255.0", "netmask_eno16777736": "255.255.255.0", "netmask_lo": "255.0.0.0", "network_eno16777736": "11.0.1.0", "network_lo": "127.0.0.0", "operatingsystem": "RedHat", "operatingsystemmajrelease": "7", "operatingsystemrelease": "7.2", "os": {"family": "RedHat", "name": "RedHat", "release": {"full": "7.2", "major": "7", "minor": "2"}}, "osfamily": "RedHat", "partitions": {"sda1": {"filesystem": "xfs", "mount": "/boot", "size": "614400", "uuid": "570828b6-d779-4967-96fd-b2b0f526d1c7"}, "sda2": {"filesystem": "swap", "size": "4194304", "uuid": "1c352bba-419c-45f9-aee4-33f561fa3adf"}, "sda3": {"filesystem": "xfs", "mount": "/", "size": "37132288", "uuid": "c058400b-3be7-4902-ba95-8c08abf428ba"}}, "path": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", "physicalprocessorcount": 2, "processor0": "Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz", "processor1": "Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz", "processorcount": 2, "processors": {"count": 2, "models": ["Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz", "Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz"], "physicalcount": 2}, "productname": "VMware Virtual Platform", "ps": "ps -ef", "rubyplatform": "x86_64-linux", "rubysitedir": "/usr/local/share/ruby/site_ruby/", "rubyversion": "2.0.0", "selinux": true, "selinux_config_mode": "enforcing", "selinux_config_policy": "unknown", "selinux_current_mode": "enforcing", "selinux_enforced": true, "selinux_policyversion": "28", "serialnumber": "VMware-56 4d 8d ec 75 14 da 3d-86 a0 ac 4c 74 af 86 c8", "sshecdsakey": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNs6cwFKInCtX1eUrXl7PootQTQ7btd+aA3DcTtH9TihD252WnC/cUisILy38hGoqxm8+d2aw+W7HqHQOsd2HP4=", "sshed25519key": "AAAAC3NzaC1lZDI1NTE5AAAAIMd6dtJf4QsdSa0cabaGWG6eX2vH0uN/BLrsrmdSAATV", "sshfp_ecdsa": "SSHFP 3 1 c0cb53b2e9cb7e79e12913112aeae09da9e4c494\nSSHFP 3 2 f083051fe458b4f5edcfa529a92e1967b4d9d64f5528346eb04d0660bc98a36c", "sshfp_ed25519": "SSHFP 4 1 039897f1b97cba8ea06efb6240b02db31a513312\nSSHFP 4 2 3d239224bf4ee372299910c034770f38fc09248b1729cb765ae8233fc4967f9a", "sshfp_rsa": "SSHFP 1 1 5437165980a87d0243b80b9396f06b1702b2dfe2\nSSHFP 1 2 ae37485b3d438a68754088e2cecc6e5d34d7f2930f5264ec045b653e666c6fc0", "sshrsakey": "AAAAB3NzaC1yc2EAAAADAQABAAABAQCwbc57oJONFHN/fq0eMlr5I9RmXMCIErK0hi9db1rIyUiJ+G8TdKGD3r3WBGez2MJrv0UbecNkU3kSx/UeC7anhtMFfGenBdM7ftXuTeFnNpLaJKHMvaG6IakET3+vXd7QJcSt4IFzL7koWD/31dU4v9UicPt4DXDXjggFuwDVTNI+4ff3LbzoOMhhf2e81VAogfSLz7SSxDQ7OUYHfI+p/hTf7YN5cAObRrzfi08AXQ3Wa4jF4nXRxeOewGyUJR3r+crUL8XyVP75ddUMG/QvjRbwAf0vdMnDuM/Z/MEWr6cZYO49ZvWMMAXlNaXQxgtxkmeZGz/2hC64xUPwcTtr", "swapfree": "2.00 GB", "swapfree_mb": "2047.47", "swapsize": "2.00 GB", "swapsize_mb": "2048.00", "system_uptime": {"days": 1, "hours": 25, "seconds": 93468, "uptime": "1 day"}, "timezone": "PDT", "type": "Other", "uniqueid": "00000000", "uptime": "1 day", "uptime_days": 1, "uptime_hours": 25, "uptime_seconds": 93468, "uuid": "EC8D4D56-1475-3DDA-86A0-AC4C74AF86C8", "virtual": "vmware"
}

2. playbook变量与引用 

        2.1 通过Inventory文件定义主机以及主机组变量

                首先,我们来看下对应的inventory文件,Ansible默认的Inventory文件是INI格式,例如:

[root@ansible01 ansible]# cat /etc/ansible/hosts |grep -v "^#"|grep -v "^$"
11.0.1.18	key=118
11.0.1.19	key=119
[nginx]
11.0.1.1[8:9]
[nginx:vars]
ansible_python_interpreter=/usr/bin/python2.7

我们在编写个playbook来验证变量能否引用:

#1.[root@ansible01 ansible]# cat /etc/ansible/variable.yaml 
---
- hosts: allgather_facts: Falsetasks:- name: diplay Host Variable from hostfiledebug: msg="The {{ inventory_hostname }} Value is {{ key }}"
#2.[root@ansible01 ansible]# ansible-playbook variable.yaml 
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory sourcePLAY [all] ********************************************************************************************************************************************************************************TASK [diplay Host Variable from hostfile] *************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "The 11.0.1.18 Value is 118"
}
ok: [11.0.1.19] => {"msg": "The 11.0.1.19 Value is 119"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

发现变量调用成功,我们修改下/etc/ansible/hosts文件

[root@ansible01 ansible]# cat /etc/ansible/hosts |grep -v "^#"|grep -v "^$"
#11.0.1.18	key=118
#11.0.1.19	key=119
[nginx]
11.0.1.1[8:9]
[nginx:vars]
ansible_python_interpreter=/usr/bin/python2.7
key=nginx

在运行variable.yaml试试,看看效果:

[root@ansible01 ansible]# ansible-playbook variable.yaml 
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable2.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable2.yaml as an inventory sourcePLAY [all] ********************************************************************************************************************************************************************************TASK [diplay Host Variable from hostfile] *************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "The 11.0.1.18 Value is nginx"
}
ok: [11.0.1.19] => {"msg": "The 11.0.1.19 Value is nginx"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

        2.2 通过/etc/ansible/下的文件定义主机以及主机组变量     

我们可以在/etc/ansible下新建host_vars和group_vars目录来针对主机和主机组定义的变量,我们看看目录结构:

[root@ansible01 hosts_vars]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
├── group_vars
│   └── nginx
├── hosts
├── hosts_vars
│   ├── 11.0.1.18
│   └── 11.0.1.19
├── inventory
│   ├── docker
│   └── hosts
├── roles
└── variable.yaml

 我们查看变量目录下文本内容:

[root@ansible01 ansible]# head group_vars/nginx 
key: nginx
[root@ansible01 ansible]# head hosts_vars/*
==> hosts_vars/11.0.1.18 <==
key: 11.0.1.18==> hosts_vars/11.0.1.19 <==
key: 11.0.1.19

删除/etc/ansible/hosts文件下的key定义:

[root@ansible01 ansible]# cat /etc/ansible/hosts |grep -v "^#"|grep -v "^$"
[nginx]
11.0.1.1[8:9]
[nginx:vars]
ansible_python_interpreter=/usr/bin/python2.7

再次运行variable.yaml看看输出:

ansible-playbook      ansible-playbook-2    ansible-playbook-2.7  ansible-pull          ansible-pull-2        ansible-pull-2.7      
[root@ansible01 ansible]# ansible-playbook variable.yaml 
[WARNING]:  * Failed to parse /etc/ansible/hosts_vars/11.0.1.18 with ini plugin: Invalid host pattern 'key:' supplied, ending in ':' is not allowed, this character is reserved to provide
a port.
[WARNING]: Unable to parse /etc/ansible/hosts_vars/11.0.1.18 as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/hosts_vars/11.0.1.19 with ini plugin: Invalid host pattern 'key:' supplied, ending in ':' is not allowed, this character is reserved to provide
a port.
[WARNING]: Unable to parse /etc/ansible/hosts_vars/11.0.1.19 as an inventory source
[WARNING]: Unable to parse /etc/ansible/hosts_vars as an inventory source
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory sourcePLAY [all] ********************************************************************************************************************************************************************************TASK [diplay Host Variable from hostfile] *************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "The 11.0.1.18 Value is nginx"
}
ok: [11.0.1.19] => {"msg": "The 11.0.1.19 Value is nginx"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

 2.3 通过ansible-playbook命令行传入

我们先清除所有的变量key设置,然后再运行命令:

#1.清空变量设置
[root@ansible01 ansible]# echo " " >group_vars/nginx
[root@ansible01 ansible]# echo " " >hosts_vars/11.0.1.18
[root@ansible01 ansible]# echo " " >hosts_vars/11.0.1.19
#2.运行命令
[root@ansible01 ansible]# ansible-playbook variable.yaml -e "key=wyx"
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory sourcePLAY [all] ********************************************************************************************************************************************************************************TASK [diplay Host Variable from hostfile] *************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "The 11.0.1.18 Value is wyx"
}
ok: [11.0.1.19] => {"msg": "The 11.0.1.19 Value is wyx"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

          2.4 在playbook文件内使用vars

修改variable.yaml如下:

[root@ansible01 ansible]# cat variable.yaml 
---
- hosts: allgather_facts: Falsevars:key: Ansible_nginxtasks:- name: diplay Host Variable from hostfiledebug: msg="The {{ inventory_hostname }} Value is {{ key }}"

再次运行:

[root@ansible01 ansible]# ansible-playbook variable.yaml 
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory sourcePLAY [all] ********************************************************************************************************************************************************************************TASK [diplay Host Variable from hostfile] *************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "The 11.0.1.18 Value is Ansible_nginx"
}
ok: [11.0.1.19] => {"msg": "The 11.0.1.19 Value is Ansible_nginx"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

        2.5 使用register内的变量

我们假设有2个task,如何让第二个task引用第一个task命令的结果座位变量呢?看下面这个例子:

[root@ansible01 ansible]# cat variable2.yaml 
---
- hosts: allgather_facts: Falsetasks:- name: register varibaleshell: hostnameregister: info - name: display variabledebug: msg="The {{ inventory_hostname }} Value is {{ info }}"

 我们在运行看看结果:

[root@ansible01 ansible]# ansible-playbook variable2.yaml 
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable2.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable2.yaml as an inventory sourcePLAY [all] ********************************************************************************************************************************************************************************TASK [register varibale] ******************************************************************************************************************************************************************
changed: [11.0.1.19]
changed: [11.0.1.18]TASK [display variable] *******************************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "The 11.0.1.18 Value is {'stderr_lines': [], u'changed': True, u'end': u'2024-04-28 15:21:18.866921', 'failed': False, u'stdout': u'ansible01', u'cmd': u'hostname', u'rc': 0, u'start': u'2024-04-28 15:21:18.862297', u'stderr': u'', u'delta': u'0:00:00.004624', 'stdout_lines': [u'ansible01']}"
}
ok: [11.0.1.19] => {"msg": "The 11.0.1.19 Value is {'stderr_lines': [], u'changed': True, u'end': u'2024-04-28 00:20:19.627787', 'failed': False, u'stdout': u'ansible02', u'cmd': u'hostname', u'rc': 0, u'start': u'2024-04-28 00:20:19.623874', u'stderr': u'', u'delta': u'0:00:00.003913', 'stdout_lines': [u'ansible02']}"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

我们看到返回的结果是一串python字典,我们在修改下取值后再运行:

#1.修改取值
[root@ansible01 ansible]# cat variable2.yaml 
---
- hosts: allgather_facts: Falsetasks:- name: register varibaleshell: hostnameregister: info - name: display variabledebug: msg="The {{ inventory_hostname }} Value is {{ info['stdout'] }}"
#2.执行查看结果
[root@ansible01 ansible]# ansible-playbook variable2.yaml 
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable2.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable2.yaml as an inventory sourcePLAY [all] ********************************************************************************************************************************************************************************TASK [register varibale] ******************************************************************************************************************************************************************
changed: [11.0.1.19]
changed: [11.0.1.18]TASK [display variable] *******************************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "The 11.0.1.18 Value is ansible01"
}
ok: [11.0.1.19] => {"msg": "The 11.0.1.19 Value is ansible02"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

        2.6 使用vars_prompt传入

 Ansible还支持在运行playbook的时候,通过交互式的方式给定义好的参数传入变量值,如下面这个例子:

[root@ansible01 ansible]# cat variable3.yaml 
---
- hosts: allgather_facts: Falsevars_prompt:- name: "one"prompt: "please input one value"private: no- name: "two"prompt: "please input two value"default: 'good'private: yestasks:- name: display one variabledebug: msg="one value is {{ one }}"- name: display two variabledebug: msg="two value is {{ two }}"

运行:

[root@ansible01 ansible]# ansible-playbook variable2.yaml 
[WARNING]: Unable to parse /etc/ansible/roles as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable.yaml as an inventory source
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with auto plugin: no root 'plugin' key found, '/etc/ansible/variable2.yaml' is not a valid YAML inventory plugin config file
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with yaml plugin: YAML inventory has invalid structure, it should be a dictionary, got: <class
'ansible.parsing.yaml.objects.AnsibleSequence'>
[WARNING]:  * Failed to parse /etc/ansible/variable2.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /etc/ansible/variable2.yaml as an inventory source
please input one value: hello
please input two value [good]: PLAY [all] ********************************************************************************************************************************************************************************TASK [display one variable] ***************************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "one value is hello"
}
ok: [11.0.1.19] => {"msg": "one value is hello"
}TASK [display two variable] ***************************************************************************************************************************************************************
ok: [11.0.1.18] => {"msg": "two value is good"
}
ok: [11.0.1.19] => {"msg": "two value is good"
}PLAY RECAP ********************************************************************************************************************************************************************************
11.0.1.18                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
11.0.1.19                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

看yaml中,one被定义非私有变量,two定义为私有变量并提供了默认值good


http://www.ppmy.cn/news/1448469.html

相关文章

【Unity】修改模型透明度

在 Unity 中修改模型透明度主要有两种方法&#xff1a;通过材质和通过着色器。以下是两种方法的步骤和解释&#xff1a; 方法 1&#xff1a;通过材质 在 Unity 编辑器中&#xff0c;选择你想要修改透明度的模型。在 Inspector 窗口中&#xff0c;找到模型的 Renderer 组件&am…

JS字符串方法

文章目录 1.length&#xff1a;返回字符串的长度。2.charAt(index)&#xff1a;返回指定索引位置的字符。3.concat(str1, str2, ...)&#xff1a;将两个或多个字符串连接起来。4.indexOf(searchValue, startIndex)&#xff1a;返回指定值在字符串中第一次出现的位置。5.lastInd…

2024年五一数学建模C题完整解题思路代码

2024年第二十一届五一数学建模竞赛题目 C题 煤矿深部开采冲击地压危险预测 煤炭是中国的主要能源和重要的工业原料。然而&#xff0c;随着开采深度的增加&#xff0c;地应力增大&#xff0c;井下煤岩动力灾害风险越来越大&#xff0c;严重影响着煤矿的安全高效开采。在各类深…

RabbitMQ是如何保证消息不被重复消费,或者说是如何保证消息消费时的幂等性的

目录 面试官:RabbitMQ是如何保证消息不被重复消费?或者说是如何保证消息消费时的幂等性的1. 使用唯一业务标识2. 使用RabbitMQ的消息去重插件3. 使用业务逻辑实现幂等性4. 使用消息属性和死信队列5. 使用Spring Boot的重试机制该文章专注于面试,面试只要回答关键点即可,不需…

OPPO Reno10Pro/Reno11/K10手机强解BL刷root权限KSU内核抓包刷机救砖

OPPO Reno10Pro/Reno11/K10手机虽然发布时间并不久&#xff0c;但由于天玑处理器的体质&#xff0c;已经支持强制解锁BL了&#xff0c;该漏洞来自第三方工具适配&#xff0c;支持OPPO天机8100/8200刷机救砖解锁BL不需要等待官方深度测试直接实现。解锁BL后的OPPO Reno10Pro/Ren…

【华为】路由综合实验(基础)

【华为】路由综合实验 实验需求拓扑配置AR1AR2AR3AR4AR5PC1PC2 查看通信OSPF邻居OSPF路由表 BGPBGP邻居BGP 路由表 配置文档 实验需求 ① 自行规划IP地址 ② 在区域1里面 启用OSPF ③ 在区域1和区域2 启用BGP&#xff0c;使AR4和AR3成为eBGP&#xff0c;AR4和AR5成为iBGP对等体…

【Android】实现 MVVM 架构,创建 ViewModel、LiveData 和数据绑定等组件在 XML 中使用数据绑定

在 Android 中实现 MVVM 架构&#xff0c;需要创建 ViewModel、LiveData 和数据绑定等组件&#xff0c;并在 XML 中使用数据绑定来将 ViewModel 的数据和 UI 绑定在一起。以下是一个简单的示例代码&#xff1a; 创建 ViewModel 类&#xff1a; public class MyViewModel exte…

【openLooKeng集成Hive连接器完整过程】

【openLooKeng集成Hive连接器完整过程】 一、摘要二、正文2.1 环境说明2.2 Hadoop安装2.2.1. 准备工作2.2.2 在协调节点coordinator上进行安装hadoop2.2.3、将Hadoop安装目录分发到从节点worker2.2.4、在协调节点coordinator上启动hadoop集群2.3 MySQL安装2.4 Hive安装及基本操…