本节内容:html
迭代node
模板(JInjia2相关)linux
Jinja2相关nginx
当有须要重复性执行的任务时,web
可使用迭代机制。其使用格式为将须要迭代的内容定义为item变量引用,并经过with_items语句来指明迭代的元素列表便可。例如:apache
- name: add several users user: name={{ item }} state=present groups=wheel with_items: - testuser1 - testuser2
上面语句的功能等同于下面的语句:vim
- 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,例如:app
- name: add several users user: name={{ item.name }} state=present groups={{ item.groups }} with_items: - { name: 'testuser1', groups: 'wheel'} - { name: 'testuser2', groups: 'root'}
【注意】:item是固定变量名。
运维
假如为两台webserver安装httpd,而他们的配置文件,172.16.7.152上的httpd须要监听80端口,172.16.7.153须要监听8080端口,ServerName也是不同的,因此咱们就须要两个配置文件,这管理起来极为不便。ide
在这种状况下,咱们能够考虑在配置文件中使用变量来定义。
[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
执行完成后,去查看两个节点的配置文件,发生变量都被替换了。
参考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 获取硬件信息
连接http://www.javashuo.com/article/p-psqjmgom-o.html
使用 ansible 批量获取 IP MAC OOB 地址对应关系
连接https://www.codercto.com/a/37130.html
ansible facts获取主机ip
{{ hostvars[inventory_hostname].ansible_eth0.ipv4.address }}