自动化运维ansible --playbook

 

ansible-playbook 中变量优先级第一为 -e 参数后的定义,其二为yaml 中定义的,最后为hosts文件中定义的

 

 

 

 

 

 

[root@k8s-master ansible]# cat nginx.yml
---
- hosts: websvrs
  remote_user: root

  tasks:
    - name: install package
      yum:  name=nginx
    - name: copy template
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: restart service
    - name: start service
      service: name=nginx state=started enabled=yes

  handlers:
    - name: restart service
      service: name=nginx state=restarted

 

 

 

 

 

 

[root@centos068 ansible]# cat web1.yml ;echo '-----------' ;cat templates/for1.conf.j2
---
- hosts: kubevela
  remote_user: root
  vars:
    ports:
      - 81
      - 82
      - 83


  tasks:
    - name: copy conf
      template: src=for1.conf.j2  dest=/opt/for1.conf

-----------
{% for p in ports %}
server{
          listen {{ p }}

}
{% endfor %}

  

结果输出:

 

 

[root@centos068 ansible]# cat web3.yml;echo '--------' ;cat templates/for3.conf.j2
---
- hosts: kubevela
  remote_user: root
  vars:
    ports:
      - web1:
        port: 80
        name: web1.xq0422.com
        #rootdir: /data/website1

      - web2:
        port: 82
        name: web2.xq0422.com
        rootdir: /data/website2

      - web3:
        port: 83
        name: web3.xq0422.com
        rootdir: /data/website3

  tasks:
    - name: copy conf
      template: src=for3.conf.j2  dest=/opt/for3.conf

--------
{% for p in ports %}
server{
          listen {{ p.port }}
          service {{ p.name }}
{% if p.rootdir is defined %}
          documentroot {{ p.rootdir }}
{% endif %}
}
{% endfor %}

  结果输出:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

感谢 马哥教育

以上总结来自B站,视频资源如下:  

https://www.bilibili.com/video/BV18t411f7CN?p=1&vd_source=47e0656689d49b82033428687694518c

posted @ 2023-03-03 19:25  会bk的鱼  阅读(50)  评论(0编辑  收藏  举报