Ansible教程(7)template中的with循环与when条件判断
一、Ansible with循环
在Ansible中使用with_items进行循环迭代,适用于需要重复执行的任务。对需要进行循环时,使用固定变量名{{ itme }},然后在task中使用with_items给定要迭代的元素列表。
示例1,通过with_items安装多个软件
vi /etc/ansible/with.yml --- - hosts: 192.168.1.100 remote_user: root tasks: - name: Install Package yum: name={{ item }} state=installed #引用item获取值 with_items: #定义with_items - redis - nginx ansible-playbook while.yml
二、Ansible when条件判断
示例1:判断客户端系统判断,然后选择对应的配置文件
vi /etc/ansible/when.yml #加入如下内容 - hosts: dbservers user: root vars: - http_port: 8080 tasks: - name: install nginx yum: name=nginx - name: copy conf for centos7 template: src=nginx.conf7.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == "7" #这里的变量是取facts信息 notify: restart service - name: copy conf for centos6 template: src=nginx.conf6.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == "6" notify: restart service - name: start service service: name=nginx state=started enabled=yes handlers: - name: restart service service: name=nginx state=restarted
示例2:当远程主机FQDN名为test时,给该主机添加一个用户user10
vi test.yml - hosts: all remote_user: root vars: - username: user10 tasks: - name: create {{ username }} user user: name={{ username }} when: ansible_fqdn == "test"
版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。
评论