码迷,mamicode.com
首页 > 其他好文 > 详细

ansible 变量

时间:2018-12-23 22:13:25      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:tcp   不能   inode   了解   shell   free   ace   receive   vdi   

个人博客:zhangshoufu.com

Ansible 变量

在ansible里面灵活的使用变量会使我们的工作变得更加灵活。

变量的定义

和大多数编程语言一样,ansible变量名应该由字符、数字、下划线组成,变量名需要以字母开头,ansible内置的关键字不能作为变量名。

playbook中使用变量

[root@master_11 playbook]# cat z16.yml 
- hosts: node3
  vars:
    var_test: test_file
  tasks:
    - name: touch test file test_file
      file: path=/tmp/{{ var_test }}, state=touch

上述实例中,利用vars关键字,在当前这个playbook中进行变量的三个设置,
vars关键字的下一级定义了一个个变量,变量名为var_test,变量的值为test_file,当我们需要使用var_test变量值时,则需要用{{ 变量名 }}来引用这个变量

我们也可以定义多个变量

vars:
  var_test_1: test_file_1
  var_test_2: test_file_2

也可以使用yaml的语法定义变量

vars:
  - test_vars_1: test_file_1
  - test_vars_2: test_file_2

在定义变量的时候还能够使用类似于“属性”的方式来定义


[root@master_11 playbook]# cat z17.yml 
- hosts: node3
  vars:
    user:
      name: zsf
      groups: zsf
  tasks:
    - name: create groups zsf
      group: name={{ user.groups }} state=present

    - name: create user zsf group zsf
      user: name={{ user.name }} groups={{ user.groups }} shell=/bin/bash

执行结果

[root@master_11 playbook]# ansible-playbook z17.yml 

PLAY [node3] ***********************************************************************

TASK [Gathering Facts] **********************************************************************
ok: [10.0.0.13]

TASK [create groups zsf] ********************************************************************
changed: [10.0.0.13]

TASK [create user zsf group zsf] ****************************************************************
changed: [10.0.0.13]

PLAY RECAP *********************************************************************************
10.0.0.13                  : ok=3    changed=2    unreachable=0    failed=0   

[root@node_2_13 ~]# id zsf
uid=1000(zsf) gid=100(users) groups=100(users),1000(zsf)

我们可以利用数组的方式来调用这个变量的属性{{ user[‘name‘] }
如果我们利用yaml语法来书写这个变量引用,就必须在变量外面加上双引号,否则语法会报错,使用 = 号的时候可以不用考虑这个

[root@master_11 playbook]# cat z17.yml 
- hosts: node3
  vars:
    user:
      name: zsf
      groups: zsf
  tasks:
    - name: create file zsf
      file:
        name: "{{ user.groups }}"
        state: touch

执行结果

[root@master_11 playbook]# ansible-playbook z17.yml 

PLAY [node3] ***********************************************************************

TASK [Gathering Facts] *****************************************************************
ok: [10.0.0.13]

TASK [create file zsf] ***********************************************************************
changed: [10.0.0.13]

PLAY RECAP ************************************************************************
10.0.0.13                  : ok=2    changed=1    unreachable=0    failed=0 
[root@node_2_13 ~]# find / -name zsf
/root/zsf

在别的文件里面定义变量

我们可以变变量定义在别的文件里面,然后在playbook里面调用这个变量,我们为什么这样做,我们有的时候可能希望能查看我们的playbook,但是却不想让他们完全能看懂,这个时候我们就可以在playbook里面多定义一些变量,然后把变量对应的信息放在另外一个文件里面,然后在playbook里面自己调用

在别的文件里面定义的方式语法和上面介绍的哪几种差不多,下面请看touch_file_vars.yml文件

[root@master_11 playbook]# cat touch_file_vars.yml 
test_file_1: file1
test_file_3: file3
file:
  test_5: fil5
  test_6: ifle6

[root@master_11 playbook]# cat z19.yml 
- hosts: node3
  vars_files:
    - /playbook/touch_file_vars.yml
  tasks:
    - name: touch file
      file:
        name: "{{ test_file_1 }}"
        state: touch
    - name: touch file
      file: name={{test_file_3}} state=touch
    - name: touch file
      file: name={{ file.test_5 }} state=touch
    - name: touch file
      file: name={{ file[‘test_6‘] }} state=touch

我们也可以给同时使用varsvars_files两个

在roles里面定义变量

我们在对应roles里面的vars目录下的main.yml里面添加上对应的变量信息,在tasks里面直接调用

[root@master_11 nginx]# tree 
.
├── roles
│   └── ansible
│       ├── tasks
│       │   └── main.yml
│       └── vars
│           └── main.yml
└── site.yml

[root@master_11 nginx]# cat site.yml 
- hosts: node3
  remote_user: root
  roles:
    - nginx

[root@master_11 nginx]# cat roles/ansible/vars/main.yml 
touch_file: file1
touch:
  file: file2

[root@master_11 nginx]# cat roles/ansible/tasks/main.yml 
- name: roles touch file1
  file: name={{  touch_file }} state=touch

- name: roles touch file2
  file: name={{ touch[‘file‘] }} state=touch

执行结果

[root@master_11 nginx]# ansible-playbook site.yml 

PLAY [node3] *********************************************************************************

TASK [Gathering Facts] **********************************************************
ok: [10.0.0.13]

TASK [ansible : roles touch file1] *************************************************************
changed: [10.0.0.13]

TASK [ansible : roles touch file2] *************************************************************
changed: [10.0.0.13]

PLAY RECAP ******************************************************************
10.0.0.13                  : ok=3    changed=2    unreachable=0    failed=0 

Ansible register注册变量和setup模块获取主机信息

register(?rej?st?r),寄存器。用于注册一个变量,保存命令的结果(shell或者command模块),这个比那辆可以在后面的task、when语句或模板文件中使用,该指定用在循环中会有不同,

[root@master_11 playbook]# cat register.yaml 
- hosts: node3
  tasks:
    - shell: pwd
      register: pwd_status

    - name: print pwd_ststus value
      debug: msg={{ pwd_status }}

register接受到的值需要配个debug模块来输出对应的值

TASK [print pwd_ststus value] *******************************************************************************************************
ok: [10.0.0.13] => {
    "msg": {
        "changed": true,                        // 改变状态
        "cmd": "pwd",                           // 执行命令
        "delta": "0:00:00.002705",              // 
        "end": "2018-11-14 23:18:40.941321",    // 命令执行的结束时间
        "failed": false,                        // 失败为假,即为真
        "rc": 0,                                // 0成功,非0失败
        "start": "2018-11-14 23:18:40.938616",  // 开始的时间
        "stderr": "",                           // 单行显示输入的值
        "stderr_lines": [],                     // 多行显示输入的值
        "stdout": "/root",                      // 一行赋值
        "stdout_lines": [                       // 以列表的形式赋值
            "/root"
        ]
    }
}

debug模块可以输出register模块中对应的变量属性。

实验测试:
在每个主机的/tmp目录下生产一个以自己主机名为目录名称的目录

[root@master_11 playbook]# cat register.yaml 
- hosts: all
  tasks:
    - shell: hostname
      register: Hostname

    - name: print pwd_ststus value
      file: name=/tmp/{{ Hostname.stdout }} state=touch

此步骤可以放在zabbix-agent端自动注册的时候,填写的hostsname主机名,可以使用这种方式来完成所有服务器agent端的更改

ansible setup收集静态信息

ansible的setup类似于saltstack的grains静态信息收集,收集一些主机硬件信息等等
playets会自动调用此模块来收集有关远程主机的有用变量可以在剧本中使用。 它也可以通过`/usr/bin/ansible‘直接执行来检查哪些变量可供主机使用。 Ansible提供了很多关于系统的“事实”,自动。 Windows目标也支持此模块。

使用setup模块必须开启gather_facts: true否则获取信息失效
为了方便展示下面的信息获取并不完全。可以自行执行查看

[root@master_11 playbook]# ansible node3 -m setup
10.0.0.13 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [ 这台机器上所有的IP地址
            "10.0.3.15", 
            "10.0.0.13"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::a00:27ff:fe9c:93cb", 
            "fe80::a00:27ff:feb0:3ef4"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64",           //系统版本
        "ansible_bios_date": "12/01/2006", 
        "ansible_bios_version": "VirtualBox",       //底层虚拟化技术
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-862.el7.x86_64", 
            "LANG": "en_US.UTF-8", 
            "biosdevname": "0", 
            "net.ifnames": "0", 
            "quiet": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "UUID=c6626d0f-f1f1-44b7-8892-eb698c1f3b26"
        }, 
        "ansible_date_time": {
            "date": "2018-11-14", 
            "day": "14", 
            "epoch": "1542210418", 
            "hour": "23", 
            "iso8601": "2018-11-14T15:46:58Z", 
            "iso8601_basic": "20181114T234658121654", 
            "iso8601_basic_short": "20181114T234658", 
            "iso8601_micro": "2018-11-14T15:46:58.121733Z", 
            "minute": "46", 
            "month": "11", 
            "second": "58", 
            "time": "23:46:58", 
            "tz": "CST", 
            "tz_offset": "+0800", 
            "weekday": "Wednesday", 
            "weekday_number": "3", 
            "weeknumber": "46", 
            "year": "2018"
        }, 
        "ansible_default_ipv4": {
            "address": "10.0.3.15", 
            "alias": "eth1", 
            "broadcast": "10.0.3.255", 
            "gateway": "10.0.3.2", 
            "interface": "eth1", 
            "macaddress": "08:00:27:9c:93:cb", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "10.0.3.0", 
            "type": "ether"
        }, 
        "ansible_default_ipv6": {}, 
        "ansible_device_links": {
            "ids": {
                "sda": [
                    "ata-VBOX_HARDDISK_VBf4f08379-1a528c86"
                ], 
                "sda1": [
                    "ata-VBOX_HARDDISK_VBf4f08379-1a528c86-part1"
                ], 
                "sda2": [
                    "ata-VBOX_HARDDISK_VBf4f08379-1a528c86-part2"
                ], 
                "sda3": [
                    "ata-VBOX_HARDDISK_VBf4f08379-1a528c86-part3"
                ], 
                "sr0": [
                    "ata-VBOX_CD-ROM_VB2-01700376"
                ]
            }, 
            "labels": {}, 
            "masters": {}, 
            "uuids": {
                "sda1": [
                    "126ba328-10ad-45db-8783-50b82860c971"
                ], 
                "sda2": [
                    "86e9ae79-1624-4214-ad81-647867c6a254"
                ], 
                "sda3": [
                    "c6626d0f-f1f1-44b7-8892-eb698c1f3b26"
                ]
            }
        }, 
        "ansible_devices": {
            "sda": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "ata-VBOX_HARDDISK_VBf4f08379-1a528c86"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": []
                }, 
                "model": "VBOX HARDDISK", 
                "partitions": {
                    "sda1": {
                        "holders": [], 
                        "links": {
                            "ids": [
                                "ata-VBOX_HARDDISK_VBf4f08379-1a528c86-part1"
                            ], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "126ba328-10ad-45db-8783-50b82860c971"
                            ]
                        }, 
                        "sectors": "2097152", 
                        "sectorsize": 512, 
                        "size": "1.00 GB", 
                        "start": "2048", 
                        "uuid": "126ba328-10ad-45db-8783-50b82860c971"
                    }, 
                    "sda2": {
                        "holders": [], 
                        "links": {
                            "ids": [
                                "ata-VBOX_HARDDISK_VBf4f08379-1a528c86-part2"
                            ], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "86e9ae79-1624-4214-ad81-647867c6a254"
                            ]
                        }, 
                        "sectors": "2097152", 
                        "sectorsize": 512, 
                        "size": "1.00 GB", 
                        "start": "2099200", 
                        "uuid": "86e9ae79-1624-4214-ad81-647867c6a254"
                    }, 
                    "sda3": {
                        "holders": [], 
                        "links": {
                            "ids": [
                                "ata-VBOX_HARDDISK_VBf4f08379-1a528c86-part3"
                            ], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "c6626d0f-f1f1-44b7-8892-eb698c1f3b26"
                            ]
                        }, 
                        "sectors": "100661248", 
                        "sectorsize": 512, 
                        "size": "48.00 GB", 
                        "start": "4196352", 
                        "uuid": "c6626d0f-f1f1-44b7-8892-eb698c1f3b26"
                    }
                }, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "104857600", 
                "sectorsize": "512", 
                "serial": "VBf4f08379", 
                "size": "50.00 GB", 
                "support_discard": "0", 
                "vendor": "ATA", 
                "virtual": 1
            }, 
            "sr0": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "ata-VBOX_CD-ROM_VB2-01700376"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": []
                }, 
                "model": "CD-ROM", 
                "partitions": {}, 
                "removable": "1", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "2097151", 
                "sectorsize": "512", 
                "size": "1024.00 MB", 
                "support_discard": "0", 
                "vendor": "VBOX", 
                "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.5.1804", 
        "ansible_dns": {
            "nameservers": [
                "114.114.114.114", 
                "202.106.195.68"
            ], 
            "search": [
                "DHCP"
            ]
        }, 
        }, 
        "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_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.13", 
                "broadcast": "10.0.0.255", 
                "netmask": "255.255.255.0", 
                "network": "10.0.0.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::a00:27ff:feb0:3ef4", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "08:00:27:b0:3e:f4", 
            "module": "e1000", 
            "mtu": 1500, 
            "pciid": "0000:00:03.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_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.3.15", 
                "broadcast": "10.0.3.255", 
                "netmask": "255.255.255.0", 
                "network": "10.0.3.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::a00:27ff:fe9c:93cb", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "08:00:27:9c:93:cb", 
            "module": "e1000", 
            "mtu": 1500, 
            "pciid": "0000:00:08.0", 
            "promisc": false, 
            "speed": 1000, 
            "timestamping": [
                "tx_software", 
                "rx_software", 
                "software"
            ], 
            "type": "ether"
        }, 
        "ansible_fips": false, 
        "ansible_form_factor": "Other", 
        "ansible_fqdn": "node_1_13", 
        "ansible_hostname": "node_1_13", 
        "ansible_interfaces": [
            "lo", 
            "eth1", 
            "eth0"
        ], 
        "ansible_is_chroot": false, 
        "ansible_iscsi_iqn": "", 
        "ansible_kernel": "3.10.0-862.el7.x86_64", 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "127.0.0.1", 
                "broadcast": "host", 
                "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_machine": "x86_64", 
        "ansible_machine_id": "12db65a1691e40f7847e2a5d308c8f00", 
        "ansible_memfree_mb": 2239, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 2550, 
                "used": 409
            }, 
            "real": {
                "free": 2239, 
                "total": 2959, 
                "used": 720
            }, 
            "swap": {
                "cached": 0, 
                "free": 1023, 
                "total": 1023, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 2959, 
        "ansible_mounts": [
            {
                "block_available": 11817433, 
                "block_size": 4096, 
                "block_total": 12576513, 
                "block_used": 759080, 
                "device": "/dev/sda3", 
                "fstype": "xfs", 
                "inode_available": 25096742, 
                "inode_total": 25165312, 
                "inode_used": 68570, 
                "mount": "/", 
                "options": "rw,relatime,attr2,inode64,noquota", 
                "size_available": 48404205568, 
                "size_total": 51513397248, 
                "uuid": "c6626d0f-f1f1-44b7-8892-eb698c1f3b26"
            }, 
            {
                "block_available": 227975, 
                "block_size": 4096, 
                "block_total": 259584, 
                "block_used": 31609, 
                "device": "/dev/sda1", 
                "fstype": "xfs", 
                "inode_available": 523962, 
                "inode_total": 524288, 
                "inode_used": 326, 
                "mount": "/boot", 
                "options": "rw,relatime,attr2,inode64,noquota", 
                "size_available": 933785600, 
                "size_total": 1063256064, 
                "uuid": "126ba328-10ad-45db-8783-50b82860c971"
            }
        ], 
        "ansible_nodename": "node_1_13", 
        "ansible_os_family": "RedHat", 
        "ansible_pkg_mgr": "yum", 
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz"
        ], 
              "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": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMWbZiWtR0iX8Y3xWzETAEl2Iyf39TEvYw5roL4L+KuBx4aqta21hIwAtIhGpsIRnLtQY8+lFWrSSKQ4E/yUGog=", 
        "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIPQ3ZSrwZlha3lldVDilnH0TufWaaZ5kcNvTg7VtLpZ4", 
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQC2xuJGT5L46NKmMmctcZjxMvUGHZU5loYzsCarF1L/cOHsUlmIurhOIEnYFXKtd3qsy4ExesbBtDvqBQz5gSG38CkM1wLCO1YKJ0XQC88yex0lFk0qgXaD92YI4nUN1a53UTKoIEGgJroUMMQGd2C4EFyKf0uVOsO8NQroH+ooEV77ooocGLOSzHKoBSQFy8NA2j7XkYrLVGy2Kr9s12kFFtf9dMI1uHCWgx+kcDE5Rw3JRNIp6hAQsOn0OiSA7SKFoUbkEcSEzRRm4DlAOgKtiKSAMef4NKo4Kb2YJSqj6pwq2Lrt+jYnM0gG2rjMrV9r4sCvVkmMYuuMGtmyhyC1", 
        "ansible_swapfree_mb": 1023, 
        "ansible_swaptotal_mb": 1023, 
        "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": "innotek GmbH", 
        "ansible_uptime_seconds": 2797, 
        "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": "virtualbox", 
        "gather_subset": [
            "all"
        ], 
        "module_setup": true
    }, 
    "changed": false
}

上面执行ansible node3 -M setup返回的结果是一个json格式的字符串,为了方便优秀的您阅读,ansible已经将格式化后的json 信息返回到了控制台中,返回的信息很全,比如:
ansible_all_ipv4_addresses:返回node3这台机器上的所有IPv4 address
ansible_bios_version:返回的是当前使用的虚拟化技术

输出指定的内容

上述我们直接setup输出的是全部信息,但是我们只想看到指定的,可以使用下属方式开获取指定的内容

[root@master_11 playbook]# ansible node3 -m setup -a "filter=ansible_all_ipv4_addresses"
10.0.0.13 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.0.3.15", 
            "10.0.0.13"
        ]
    }, 
    "changed": false
}

我们肯定不能把ansible获取的key记录的那么清楚,这么长谁能记得住,所以ansible为了解决这个反人类的,他支持通配符,我们可以在知道的内容前面或后面添加上通配符*来完成模糊匹配

[root@master_11 playbook]# ansible node3 -m setup -a "filter=*address*"
10.0.0.13 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.0.3.15", 
            "10.0.0.13"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::a00:27ff:fe9c:93cb", 
            "fe80::a00:27ff:feb0:3ef4"
        ]
    }, 
    "changed": false
}

配合debug模块输出setup获取到的值

[root@master_11 playbook]# cat z7.yaml 
- hosts: node3
  gather_facts: true
  tasks:
    - name: obtain node3 hostname
      debug: msg={{ ansible_hostname }}

    - name: obtain eth1 ipv4 address
      debug: msg={{ ansible_eth1.ipv4.address }}

    - name: obtain eth0 ipv4 address 
      debug: msg={{ ansible_default_ipv4.address }}
      when: ansible_default_ipv4.alias == "eth0"

debug引用setup获取到的值的时候,按照层级的方式来调取,分级用.来表示;获取eth0 IP地址的时候,我们用的ansible_default_ipv4.address这个会获取到node3主机里面所有的IP地址,然后我们用when判断来只输出eth0的IP地址,当when后面的条件为真才会执行它上面的tasks动作

执行结果:

[root@master_11 playbook]# ansible-playbook z7.yaml 

PLAY [node3] ***********************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [10.0.0.13]

TASK [obtain node3 hostname] ***********************************************************
ok: [10.0.0.13] => {
    "msg": "node_1_13"
}

TASK [obtain eth1 ipv4 address] ************************************************************
ok: [10.0.0.13] => {
    "msg": "10.0.3.15"
}

TASK [obtain eth0 ipv4 address] *******************************************************
skipping: [10.0.0.13]

PLAY RECAP ***************************************************************************
10.0.0.13                  : ok=3    changed=0    unreachable=0    failed=0   

ansible setup获取client自定义的信息

ansible 默认回去目标主机的/etc/ansible/facts.d目录下查找主机中的自定义信息,并且规定,自定义信息需要写在以.fact为后缀的文件中,同时,这些以.fact为后缀的文件中的内容需要时INI格式或者是json格式的
在目标主机上node3上创建对应的目录和文件

INI格式:推荐使用,简单明了

[root@node_2_13 ~]# mkdir /etc/ansible/facts.d -p 
[root@node_2_13 ~]# cat /etc/ansible/facts.d/testinfo.fact
[test_var]
var1=This?is?the?var1
var2=This?is?the var2

Json格式

[root@node_2_13 ~]# cat /etc/ansible/facts.d/testinfo.fact
{
  "test_var":{
    "var1": "This?is?the?var1"
    "var2": "This?is?the?var2"
  }
}

在ansible服务器上执行结果如下

[root@master_11 playbook]# ansible node3 -m setup -a ‘filter=ansible_local‘
10.0.0.13 | SUCCESS => {
    "ansible_facts": {
        "ansible_local": {      //自定义的内容
            "testinfo": {       //文件名
                "test_var": {   //模块名
                    "var1": "This?is?the?var1", 
                    "var2": "This?is?the var2"
                }
            }
        }
    }, 
    "changed": false
}

用debug调用自定义的内容

[root@master_11 playbook]# cat z20.yml 
- hosts: node3
  tasks:
    - name: print node1 file var1
      debug: msg={{ ansible_local.testinfo.test_var.var1 }}

使用获取到的值

[root@master_11 playbook]# cat z20.yml 
- hosts: node3
  tasks:
    - name: print node1 file var1
      debug: msg={{ ansible_local.testinfo.test_var.var1 }}
    - name: touch var1
      shell: echo {{ ansible_local.testinfo.test_var.var1 }} >> /tmp/test_ansible.yml

提示用户输入信息并写入变量

在所有的编程语言中都有给用户交互的写法(提示用户输入对应的信息,然后赋值到一个变量中),ansible也有交互的功能,给用户提示一个输入,获取到他输入到的值然后我们在到后面引用这个变量。

[root@master_11 playbook]# cat z21.yml 
- hosts: node3
  vars_prompt:
    - name: "Name"           //变量名称,获取到的内容赋予到这个Name变量里面
      prompt: "please enter your name"    // 提示信息
    - name: "Blog"
      prompt: "please enter your blog address"
  tasks:
    - name: print var values
      debug: msg=" {{ Name }} personal blog is {{ Blog }}"

我们定义了两个变量NameBlog两个变量,然后并输入提示信息prompt设置的,当我们用户输入内容的时候在屏幕上是没有回显信息的,这种情况在我们输入密码的时候最有效,当我们想要她显示输入的内容的时候,你需要继续向下阅读

[root@master_11 playbook]# ansible-playbook z21.yml 
please enter your name: 
please enter your blog address: 

PLAY [node3] *************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************
ok: [10.0.0.13]

TASK [print var values] **************************************************************************************
ok: [10.0.0.13] => {
    "msg": " zhang shoufu personal blog is www.zhangshouuf.com"
}

PLAY RECAP ***************************************************************************************************
10.0.0.13                  : ok=2    changed=0    unreachable=0    failed=0   

我们放输入的信息在屏幕上显示出来,只需要在vars_prompt下面添加一个内容

[root@master_11 playbook]# cat z21.yml 
- hosts: node3
  vars_prompt:
    - name: "Name"
      prompt: "please enter your name"
      private: no
    - name: "Blog"
      prompt: "please enter your blog address"
      private: no
  tasks:
    - name: print var values
      debug: msg=" {{ Name }} personal blog is {{ Blog }}"

在我们定义vars_prompt中的变量时,使用private关键字,将变量的private属性设置为no即可,private: no表示变量并非私有,默认是yes,变量时私有的
执行结果:

please enter your blog address: www.zhangshoufu.com

PLAY [node3] ***********************************************************************

TASK [Gathering Facts] ***********************************************************************
ok: [10.0.0.13]

TASK [print var values] *************************************************************
ok: [10.0.0.13] => {
    "msg": " zhang shoufu personal blog is www.zhangshoufu.com"
}

PLAY RECAP ***************************************************************************
10.0.0.13                  : ok=2    changed=0    unreachable=0    failed=0   

给用户提供几个选项,并设置一个默认值

[root@master_11 playbook]# cat z22.yaml
- hosts: node3
  vars_prompt:
    - name: "Name"
      prompt: "please enter your name"
      private: no
    - name: "sex"
      prompt: "please enter your sex \n
      A: man\n
      B: female\n"
      private: no
      default: A
  tasks:
    - name: print information
      debug: msg="{{ Name}} his gender is {{ sex }}"

ansible 变量

标签:tcp   不能   inode   了解   shell   free   ace   receive   vdi   

原文地址:http://blog.51cto.com/13447608/2334328

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!