(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"