本节内容:
迭代
模板(JInjia2相关)
Jinja2相关
一、迭代
当有需要重复性执行的任务时,
可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句来指明迭代的元素列表即可。例如:
- name: add several users user: name={{ item }} state=present groups=wheel with_items: - testuser1 - testuser2
上面语句的功能等同于下面的语句:
- name: add user testuser1 user: name=testuser1 state=present groups=wheel - name: add user testuser2 user: name=testuser2 state=present groups=wheel
另外,with_items中使用的元素还可以是hashes,例如:
- name: add several users user: name={{ item.name }} state=present groups={{ item.groups }} with_items: - { name: 'testuser1', groups: 'wheel'} - { name: 'testuser2', groups: 'root'}
【注意】:item是固定变量名。
二、模板(JInjia2相关)
假如为两台webserver安装httpd,而他们的配置文件,172.16.7.152上的httpd需要监听80端口,172.16.7.153需要监听8080端口,ServerName也是不一样的,所以我们就需要两个配置文件,这管理起来极为不便。
在这种情况下,我们可以考虑在配置文件中使用变量来定义。
[root@node1 ~]# mkdir templates [root@node1 ~]# cp conf/httpd.conf templates/ [root@node1 ~]# mv templates/httpd.conf templates/httpd.conf.j2
后缀为j2表明是Jinja2模板。编辑这个模板:
[root@node1 ~]# vim templates/httpd.conf.j2
这个模板复制到每台主机上时都应该将这文件里的变量换成对应的值。这个模板就是Jinjia2模板。
设置每台主机使用的变量值:
[root@node1 ~]# vim /etc/ansible/hosts
当然这http_port和maxClients也可以在playbook中定义。但是那样我们没法区别每台主机使用不同的值了。因此我们要想让每个主机变量名相同但值不同时只能使用主机变量来定义。下面定义playbook:
[root@node1 ~]# vim apache.yml - hosts: nginx remote_user: root vars: - package: apache tasks: - name: install httpd package yum: name={{ package }} state=latest - name: install configuration file for httpd template: src=/root/conf/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf notify: - restart httpd - name: start httpd service service: enabled=true name=httpd state=started handlers: - name: restart httpd service: name=httpd state=restarted
[root@node1 ~]# ansible-playbook apache.yml
执行完成后,去查看两个节点的配置文件,发生变量都被替换了。
Ansible 使用 Template 系统
参考https://www.w3cschool.cn/automate_with_ansible/automate_with_ansible-gm1w27pd.html
本文出自https://www.w3cschool.cn/automate_with_ansible/automate_with_ansible-gm1w27pd.html
自动化运维工具Ansible入门教程(六)变量与facts
链接http://www.linuxe.cn/post-277.html
ansible facts 获取硬件信息
链接https://www.cnblogs.com/lxmhhy/p/6813953.html
使用 ansible 批量获取 IP MAC OOB 地址对应关系
链接https://www.codercto.com/a/37130.html
ansible facts获取主机ip
{{ hostvars[inventory_hostname].ansible_eth0.ipv4.address }}转载于:https://blog.51cto.com/lookingdream/2352250