ansible 變量詳解


定義變量的方法

1、 主機變量,在hosts文件中設置變量,

[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

2、組變量,

[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com

3、playbook中定義變量

- hosts: webservers
  vars:
    http_port: 80

4、 Facts 遠程獲取系統相關變量, 可以在playbook中添加  

gather_facts: no

來關閉Facts,這樣可以提高ansible的運行效率

5、遠程機器上設置facts目錄獲取變量

如果遠程受管理的機器有一個 “/etc/ansible/facts.d” 目錄,那么在該目錄中任何以 ”.fact”結尾的文件都可以在Ansible中提供局部facts.這些文件可以是JSON,INI或者任何可以返回JSON的可執行文件.

例如建設有一個 /etc/ansible/facts.d/perferences.fact文件:

[general]
asdf=1
bar=2

這將產生一個名為 “general” 的哈希表fact,里面成員有 ‘asdf’ 和 ‘bar’. 可以這樣驗證:

ansible <hostname> -m setup -a "filter=ansible_local"
結果為:
"ansible_local": {
        "preferences": {
            "general": {
                "asdf" : "1",
                "bar"  : "2"
            }
        }
 }

而且也可以在template或palybook中訪問該數據:

{{ ansible_local.preferences.general.asdf }}

6、使用運行結果得到變量

- hosts: web_servers
  tasks:
     - shell: /usr/bin/foo
       register: foo_result
       ignore_errors: True

     - shell: /usr/bin/bar
       when: foo_result.rc == 5

6、使用文件轉遞變量

把playbook置於源代碼管理之下是個很好的注意,當你可能會想把playbook源碼公開之余還想保持某些重要的變量私有.有時你也想把某些信息放置在不同的文件中,遠離主playbook文件.

- hosts: all
  remote_user: root
  vars:
    favcolor: blue
  vars_files:
    - /vars/external_vars.yml
  tasks:
  - name: this is just a placeholder
    command: /bin/echo foo

7、命令行中傳遞變量

ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"
或者使用json
--extra-vars '{"pacman":"mrs","ghosts":["inky","pinky","clyde","sue"]}'

8、訪問其他主機信息

Ansible會自動提供給你一些變量,即使你並沒有定義過它們.這些變量中重要的有 ‘hostvars’,’group_names’,和 ‘groups’.由於這些變量名是預留的,所以用戶不應當覆蓋它們. ‘environmen’ 也是預留的. hostvars可以讓你訪問其它主機的變量,包括哪些主機中獲取到的facts.如果你還沒有在當前playbook或者一組playbook的任何play中訪問那個主機,那么你可以獲取變量,但無法看到facts值. 如果數據庫服務器想使用另一個節點的某個 ‘fact’ 值,或者賦值給該節點的一個inventory變量.可以在一個模板中甚至命令行中輕松實現:

{{ hostvars['test.example.com']['ansible_distribution'] }}

另外, group_names 是當前主機所在所有群組的列表(數組).所以可以使用Jinja2語法在模板中根據該主機所在群組關系(或角色)來產生變化:

{% if 'webserver' in group_names %}
   # some part of a configuration file that only applies to webservers
{% endif %}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM