Ansible小記

1、Ansible環境變量優先級

1、執行play-book時 -e指定的ansible-playbook site.yml --tags=test -e test=test-e  

2、register 註冊的環境變量

3、role下的 vars文件夾下的環境變量

4、hosts資產下設置的環境變量

5、group/all 下的all

6、 site.yml入口文件的vars 配置的環境變量

7、 role下的default的 環境變量

我的測試環境條件目錄如下


[root@ansible ansible]# pwd
/etc/ansible
[root@ansible ansible]# cat site.yml 
- name: install compute nodes roles
  hosts: compute
  vars:
  roles:
     - { role: commen,tags: commen }
     - { role: nova, tags: nova }
     - { role: neutron, tags: neutron }
     - { role: cinder, tags: cinder }
     - { role: test, tags: test }
     
 
[root@ansible ansible]# cd roles/test/
[root@ansible test]# pwd
/etc/ansible/roles/test
[root@ansible test]# ls
defaults  files  tasks  templates  vars
[root@ansible test]#
[root@ansible test]# cd tasks/

[root@ansible tasks]# cat main.yml 
---
- name: update time
  shell: date -R
#  register: test
- name: print test 
  debug: msg="{{ test }}"

2、變量調用hosts裏面的變量,比如group/all 配置文件調用hosts 下 的變量。

cat /etc/ansible/hosts
[controller]
192.168.64.132  mgmt=192.168.64.132   pub_nic=ens37  br_ex_addr=192.168.64.130 tunnel_ip=192.168.64.132  ansible_python_interpreter="/root/venv/bin/python"

cat group_vars/all 
### neutron ####
neutron_mysql_password: admin
neutron_pass: admin
metadata_proxy_shared_secret: admin
controller_mgmt_ip: hostvars[groups['controller'][0]]['mgmt']    # 此處要和hosts下面的mgmt的ip用一個變量,此時可以用hostvars[groups['controller'][0]]['mgmt']來代替。

3、通過變量來確定是否要執行這個動作。

  比如我們通過group/all下的變量來確定要不要安裝 l3服務

[root@bogon ansible]# grep install_l3 group_vars/all 
install_l3: True #當着爲True時 代表執行,若不想執行,則爲False
查看playbook
[root@bogon tasks]# cat main.yml 
---
- name: install l3
  yum: name=router  state=latest
  when: install_l3
[root@bogon tasks]#

4、wait_for  模塊
wait_for:  
    host: "{{ inventory_hostname }}" #'{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
    port: "{{ item }}"
  with_items:
      - 5000
      - 35357

通過上面的變量的判斷就可以,選擇安裝或者不安裝。很方便!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章