ansible的變量

一、Variables Defined  In Inventory

[webservers]
app1_server http_port=8080   #app1_server的主機變量

[websevers:vars]      #webservers組的變量
one=hello
two=world

/etc/ansible/host_vars/app_server     #app_server主機變量
/etc/ansible/group_vars/webservers    #webservers主機組變量

二、Variables Defined  In Playbook

#定義單個變量
vars:      
  - name: dxx
  - age: 14

#定義變量文件
vars_files:
  - variables.yml

#定義變量交互賦值
vars_prompt:
  - name: version
    prompt: please input version
    private: no

三、Variables Defined  In Command

ansible-playbook main.yml -e 'init="begin" final="end"'          #變量賦值
ansible-playbook main.yml -e '{"init":"begin","final":"end"}'    #json字符串
ansible-playbook main.yml -e '@test.json'                        #json文件

四、Variables Defined  In Register

- hosts: mfs_node
  task:
    - shell: echo "5"
      register: result         #註冊result變量即shell命令執行的結果狀態
      ignore_errors: True      #忽略錯誤

    - debug: msg="it failed"
      when: result|failed      #若是結果爲失敗輸出debug信息,有success、failed狀態

    - debug: msg="{{result.stdout}}"  #輸出shell命令執行的結果

    - shell: /usr/bin/foo
      when: result.rc == 0   #執行錯誤,rc返回非0值

五、Variables Defined  In Roles

六、Using Variables:  About Jinja2

(1)template模板中變量的替換node

(2)template模板中使用jinja2的循環語句web

七、Facts

(1)System facts  

hostvars 記錄主機的變量                    #ns1_ip="{{hostvars.ns1.ansible_default_ipv4.address}}"    ns1爲主機名shell

groups 資源清單中的全部組               # 打印全部主機的ip     {% for host in groups %} {{hostvar[host].ansible_default_ipv4.address}} {% endfor %}json

group_names 當前主機所在的主機組名app

inventory_hosts  主控端的主機名spa

inventory_hosts_short  主控端的主機名前綴debug

inventory_dir  設備清單文件的目錄code

inventory_file  設備清單文件的名字server

(2)Local Facts

將fact文件放在遠程主機的  /etc/ansible/facts.d目錄ip

- hosts: webservers
  tasks:
    - name: Create diretory for ansible custom facts
      file: path=/etc/ansible/facts.d state=directory recurse=yes

- name: Install custom immyfactsi fact
  copy: src=myfacts.fact dest=/etc/ansible/facts.d 

- name: re-read facts after add custom fact
  setup: filter=ansible=local



cat myfacts.fact
[general]
ad=1
bar=2

八、Omitting Underfined Variable

- name: touch file with a optional mode
  file: dest={{item.path}} state=touch mode={{item.mode|default("0755")}}
  with_items:
      - path: /tmp/foo
      - path: /tmp/boo
      - path: /tmp/coo
        mode: "0444"
相關文章
相關標籤/搜索