03.变量和facts

小熊 Ansible评论496字数 1823阅读6分4秒阅读模式

体验变量

修改hosts文件,增加变量1,名为var1

[local]
自己的ip var1=var1

[local:vars]
ansible_ssh_pass=Abc123123

创建show_vars.yaml文件。

---
- hosts: all
  vars:
    var2: 2
    name: all var    
  tasks:
  - name: show {{name}}
    debug:
      msg: "var1:{{var1}} var2:{{var2}} var3:{{var3}}"

执行命令。

ansible-playbook show_vars.yaml -e "var3=3"

以上展示了变量出现的三个地方。

主机和主机组变量

创建group_varshost_vars两个文件夹,用来存储主机变量和主机组变量。

mkdir group_vars hosts_vars
echo "user: laoma" > host_vars/替换成自己的ip
echo "group_user: laowang" > group_vars/local

show_var2.yaml

---
- name: Display User Variables
  hosts: local
  tasks:
    - name: Display user variable for host {{inventory_hostname}}
      debug:
        var: user

    - name: Display group_user variable for hosts in the local group
      debug:
        var: group_user
ansible-playbook show_var2.yaml

数组变量

文件名: group_vars/local 内容如下:

app_servers:
  - app1
  - app2
  - app3

文件名: array.yml 内容如下:

---
- name: Demonstrate Array Variable
  hosts: local
  gather_facts: false  # 不收集主机信息,加快执行速度

  tasks:
    - name: Display App Servers
      debug:
        var: app_servers

    - name: Display loop App Servers
      debug:
        msg: "App Server: {{ item }}"
      loop: "{{ app_servers }}"
      loop_control:
        loop_var: item

facts

展示全部facts变量,创建show_facts.yaml

---
- name: show fact
  hosts: local
  gather_facts: true
  tasks:
    - name: show all fact
      debug:
        var: ansible_facts

    - name: show all fact format
      debug:
        msg: |
          主机名: {{ ansible_facts['hostname'] }}
          主机IP: {{ ansible_facts['default_ipv4']['address'] }}
          主机DNS: {{ ansible_facts['dns']['nameservers'] }}
          boot分区: {{ ansible_facts['devices']['vda']['partitions']['vda1']['size'] }}
          内核: {{ ansible_facts['kernel'] }}
          内存空闲: {{ ansible_facts['memfree_mb'] }}

运行起来

ansible-playbook show_facts.yaml

tag标签管理

tags.yaml

---
- name: Demonstrate Tags in Ansible
  hosts: local
  gather_facts: false

  tasks:
    - name: Install App Servers
      debug:
        msg: "Install App Server: {{ item }}"
      loop: "{{ app_servers }}"
      loop_control:
        loop_var: item
      tags:
        - install

    - name: remove App on Servers
      debug:
        msg: "Remove App on {{ item }}"
      loop: "{{ app_servers }}"
      loop_control:
        loop_var: item
      tags:
        - remove

运行起来

ansible-playbook tags.yaml --tags install
ansible-playbook tags.yaml --tags remove

weinxin
公众号
扫码订阅最新深度技术文,回复【资源】获取技术大礼包
小熊