(1)在模板中調用外部的變量,調用方式{{ xxx }}node
(2)模板中能夠使用jinja的語法,如循環、條件、宏等web
#注意: 在{% %}中使用外部變量,不能加{{}} {% for ip in ansible_all_ipv4_addresses %} {{ ip }}; {% endfor %} # group_names 主機所在組名 {% if 'node_slave' in group_names %} slave {% else %} master {% endif %}
運行過程當中在受控主機上設置變量或計算變量值shell
--- - hosts: localhost tasks: - name: set fact 1 set_fact: foo="[ 'zero' ]" - name: set fact 2 set_fact: foo="{{ foo }} + [ 'one' ]" - name: set fact 3 set_fact: foo="{{ foo }} + [ 'two', 'three' ]" - name: set fact 4 set_fact: foo="{{ foo }} + [ '{{ item }}' ]" with_items: - four - five - six - debug: var=foo 輸出: "foo": [ "zero", "one", "two", "three", "six" ]
--- - hosts: localhost vars: flag: false tasks: - name: bbbbbbbb shell: echo bbbb - name: include test #方式1 include_role: name=test - name: include test 2 #方式2 include_role: name: test - name: cccccccccc shell: echo cccccccc
注意:最好不要這樣,若是循環調用中調用前面的role,會出現死循環。tomcat
--- - hosts: localhost vars: flag: false tasks: - name: bbbbbbbb shell: echo bbbb - name: include test include_role: name=test when: flag #flag是變量,會報錯 - name: cccccccccc shell: echo cccccccc
--- - hosts: localhost vars: flag: false tasks: - name: bbbbbbbb shell: echo bbbb - name: include test include_role: name=test with_items: - myname: dxx - name: cccccccccc shell: echo cccccccc
--- - name: time wait pause: seconds=30 - name: wait on user choose pause: prompt="Warning Detected slight issue .ENTER to continue CTRL_C to quit"
用於啓動某些進程須要一些時間頗有用,如tcp端口是否鏈接app
--- - hosts: webapps tasks: - name: install tomcat6 yum: name=tomcat6 state=installed - name: service start service: name=tomcat6 state=start - name: wait for tomcat6 to start wait_for: port=8080 state=started
--- #受控主機免密登陸dan、linna、wuzhu主機 - hosts: all tasks: - name: make /opt/sshkeys dirctory file: path=/opt/sshkeys state=dirctory owner=root group=root mode=0700 - name: copy sshkey over copy: src=/keys/{{item}}.pub dest=/opt/sshkeys/{{item}}.pub owner=root group=root mode=0600 with_items: - dan - linna - wuzhu - name: make /root/.ssh dirctory file: path=/root/.ssh state=dirctory owner=root group=root mode=0700 - name: build the authorized_keys file assemable: src=/opt/sshkeys dest=/root/.ssh/authorized_keys
動態添加受管主機到playbook中ssh
- name: download foo.conf get_url: url=http://example.com/path/file.conf dest=/tmp/foo.conf mode=0440
- name: create group like 'kvm-host' group_by: key=virt_{{ ansible_virtualization_type}}_{{ ansible_virtualization_role }}
將控制主機的腳本在被管理主機上運行webapp
- name: debug debug: msg="{{ansible_distribution}}" var="aaaa"