Ansible playbook之变量引用

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: all
  gather_facts: False
  tasks:
   - name: diplay Host Variable from hostfile
     debug: 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 source

PLAY [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 source

PLAY [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 source

PLAY [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 source

PLAY [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: all
  gather_facts: False
  vars:
    key: Ansible_nginx
  tasks:
   - name: diplay Host Variable from hostfile
     debug: 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 source

PLAY [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: all
  gather_facts: False
  tasks:
   - name: register varibale
     shell: hostname
     register: info 
   - name: display variable
     debug: 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 source

PLAY [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: all
  gather_facts: False
  tasks:
   - name: register varibale
     shell: hostname
     register: info 
   - name: display variable
     debug: 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 source

PLAY [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: all
  gather_facts: False
  vars_prompt:
   - name: "one"
     prompt: "please input one value"
     private: no
   - name: "two"
     prompt: "please input two value"
     default: 'good'
     private: yes
  tasks:
   - name: display one variable
     debug: msg="one value is {{ one }}"
   - name: display two variable
     debug: 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

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值