首页 > 其他分享 >第三十七天:playbook Template 模板

第三十七天:playbook Template 模板

时间:2024-05-05 15:11:41浏览次数:10  
标签:tasks name nginx ansible 第三十七 Template root yml playbook

模板是一个文本文件,可以用于根据每个主机的不同环境而为生成不同的文件

模板文件中支持嵌套jinja2语言的指令,来实现变量,条件判断,循环等功能 需要使用template模块实现文件的复制到远程主机,但和copy模块不同,复制过去的文件每个主机可以会有所不同 一、jinja2语言 Jinja2 是一个现代的,设计者友好的,仿照 Django 模板的 Python 模板语言。 它速度快,被广泛使用,并且提供了可选的沙箱模板执行环境保证安全: 特性:   沙箱中执行   强大的 HTML 自动转义系统保护系统免受 XSS   模板继承   及时编译最优的 python 代码   可选提前编译模板的时间   易于调试。异常的行数直接指向模板中的对应行。   可配置的语法 官方网站:
http://jinja.pocoo.org/
https://jinja.palletsprojects.com/en/2.11.x/
http://docs.jinkan.org/docs/jinja2/
https://www.w3cschool.cn/yshfid/
jinja2 语言支持多种数据类型和操作: 字面量,如: 字符串:使用单引号或双引号,数字:整数,浮点数 列表:[item1, item2, ...] 元组:(item1, item2, ...) 字典:{key1:value1, key2:value2, ...} 布尔型:true/false 算术运算:+, -, *, /, //, %, ** 比较操作:==, !=, >, >=, <, <= 逻辑运算:and,or,not 流表达式:For,If,When 字面量: 表达式最简单的形式就是字面量。字面量表示诸如字符串和数值的 Python 对象。如"Hello World" 双引号或单引号中间的一切都是字符串。无论何时你需要在模板中使用一个字符串(比如函数调用、过 滤器或只是包含或继承一个模板的参数),如42,42.23 数值可以为整数和浮点数。如果有小数点,则为浮点数,否则为整数。在 Python 里, 42 和 42.0 是不 一样的 算术运算: Jinja 允许用计算值。支持下面的运算符 +:把两个对象加到一起。通常对象是素质,但是如果两者是字符串或列表,你可以用这 种方式来衔接 它们。无论如何这不是首选的连接字符串的方式!连接字符串见 ~ 运算符。 {{ 1 + 1 }} 等于 2 -:用第一个数减去第二个数。 {{ 3 - 2 }} 等于 1 /:对两个数做除法。返回值会是一个浮点数。 {{ 1 / 2 }} 等于 0.5 //:对两个数做除法,返回整数商。 {{ 20 // 7 }} 等于 2 %:计算整数除法的余数。 {{ 11 % 7 }} 等于 4 *:用右边的数乘左边的操作数。 {{ 2 * 2 }} 会返回 4 。也可以用于重 复一个字符串多次。 {{ '=' * 80 }} 会打印 80 个等号的横条\ **:取左操作数的右操作数次幂。 {{ 2**3 }} 会返回 8 比较操作符 == 比较两个对象是否相等 != 比较两个对象是否不等 > 如果左边大于右边,返回 true >= 如果左边大于等于右边,返回 true < 如果左边小于右边,返回 true <= 如果左边小于等于右边,返回 true 逻辑运算符 对于 if 语句,在 for 过滤或 if 表达式中,它可以用于联合多个表达式 and 如果左操作数和右操作数同为真,返回 true or 如果左操作数和右操作数有一个为真,返回 true not 对一个表达式取反 (expr)表达式组 true / false true 永远是 true ,而 false 始终是 false 二、template template功能:可以根据和参考模块文件,动态生成相类似的配置文件 template文件存建议放于templates目录下,且命名为 .j2 结尾 yaml/yml 文件和templates目录平级,此时playbook中指定模版文件时可不用指定路径, 目录结构如下 示例:
 ./
 ├── temnginx.yml
 └── templates
         └── nginx.conf.j2

三、template中使用流程控制 for 和 if

template中也可以使用流程控制 for 循环和 if 条件判断,实现动态生成文件功能 (1) for 循环 格式
{% for i in EXPR %}
 ...
{% endfor %}
#示例:
{% for i in range(1,10) %}
 server_name web{{i}};
{% endfor %}
(2) if 条件判断 在模版文件中还可以使用 if条件判断,决定是否生成相关的配置信息
#templnginx6.yml
- hosts: websrvs
 remote_user: root
 vars:
   nginx_vhosts:
     - web1:
       listen: 8080
       root: "/var/www/nginx/web1/"
     - web2:
       listen: 8080
       server_name: "web2.wang.org"
       root: "/var/www/nginx/web2/"
     - web3:
       listen: 8080
       server_name: "web3.wang.org"
       root: "/var/www/nginx/web3/"
 tasks:
   - name: template config to 
     template: src=nginx.conf5.j2 dest=/data/nginx5.conf
          
          
#templates/nginx.conf6.j2
{% for vhost in nginx_vhosts %}
server {
   listen {{ vhost.listen }}
   {% if vhost.server_name is defined %}
server_name {{ vhost.server_name }}   #注意缩进
   {% endif %}
root  {{ vhost.root }}                #注意缩进
}
{% endfor %}
 四、使用循环迭代 迭代:当有需要重复性执行的任务时,可以使用迭代机制 1、迭代 loop (with_items) 对迭代项的引用,固定内置变量名为"item" 要在task中使用with_items给定要迭代的元素列表 注意: ansible2.5版本后,可以用loop代替with_items 列表元素格式:   - 字符串   - 字典 范例
---
- hosts: websrvs
 remote_user: root
  
 tasks:
    - name: add several users
     user: name={{ item }} state=present groups=wheel
     with_items:
        - testuser1
        - testuser2
        - testuser3
        
#上面语句的功能等同于下面的语句
    - name: add several users
     user: name=testuser1 state=present groups=wheel
    - name: add several users
     user: name=testuser2 state=present groups=wheel
    - name: add several users
     user: name=testuser3 state=present groups=wheel

2、迭代嵌套子变量

在迭代中,还可以嵌套子变量,关联多个变量在一起使用
---
- hosts: websrvs
 remote_user: root
tasks:
   - name: add some groups
     group: name={{ item }} state=present
     with_items:
       - nginx
       - mysql
       - apache
   - name: add some users
     user: name={{ item.user }} group={{ item.group }} uid={{item.uid}}
state=present
     with_items:
       - { user: 'nginx', group: 'nginx',uid: "80" }
       - { user: 'mysql', group: 'mysql' ,uid: "3306"}
       - { user: 'apache', group: 'apache',uid: "8080"}

3、until 循环

#until为false时才会执行循环,为true则退出循环
[root@ansible ansible]#cat until.yml 
- hosts: localhost
 gather_facts: false
 tasks:
    - debug: msg="until"
      until: false
     retries: 3 #默认值即为3次
     delay: 1
[root@ansible ansible]#ansible-playbook until.yml

4、with_lines 逐行处理

[root@ansible ansible]#cat with_lines.yml
- hosts: localhost
 tasks:
    - debug: msg={{ item }}
     with_lines: ps aux

五、条件判断 when

when语句可以实现条件测试。如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否 的前提时要用到条件测试,通过在task后添加when子句即可使用jinja2的语法格式条件测试 范例:条件判断
---
- hosts: websrvs
 remote_user: root
 tasks:
   - name: "shutdown RedHat flavored systems"
     command: /sbin/shutdown -h now
     when: ansible_os_family == "RedHat"

六、分组 block

当想在满足同样条件下,执行多个任务时,就需要分组。而不再针对每个任务都是用 when
[root@ansible ansible]#cat block.yml
---
- hosts: localhost
  
 tasks:
    - block:
        - debug: msg="first"
        - debug: msg="second"
     when:
        - ansible_facts['distribution'] == "CentOS"
        - ansible_facts['distribution_major_version'] == "8"

七、changed_when

1、关闭 changed 状态 当确定某个task不会对被控制端做修改时但执行结果却显示是黄色的changed状态,可以通过changed_when: false 关闭changed状态
[root@ansible ansible]#cat test_changed.yml
---
- hosts: websrvs
  
 tasks: 
    - name: check sshd service
     shell: ps aux| grep sshd
     changed_when: false  #关闭changed状态

2、利用 changed_when 检查task返回结果

changed_when 检查task返回结果,决定是否继续向下执行
[root@ansible ansible]#cat test_changed_when.yml
---
- hosts: websrvs
 tasks:
   - name: install nginx
     yum: name=ng
- name: config file
     template: src="nginx.conf.j2" dest="/etc/nginx/nginx.conf"
     notify: restart nginx
   - name: check config
     shell: /usr/sbin/nginx -t
     register: check_nginx_config 
     changed_when:
       - check_nginx_config.stdout.find('successful') #如果执行结果中有successful
字符串,则继续执行,如果没有则停止向下执行
       - false        #nginx -t 每次成功执行是changed状态,关闭此changed状态
   - name: start service
     service: name=nginx state=started enabled=yes
 handlers:
   - name: restart nginx
     service: name=nginx state=restarted

八、滚动执行

管理节点过多导致的超时问题解决方法 默认情况下,Ansible将尝试并行管理playbook中所有的机器。对于滚动更新用例,可以使用serial关键 字定义Ansible一次应管理多少主机,还可以将serial关键字指定为百分比,表示每次并行执行的主机数 占总数的比例 范例:
#vim test_serial.yml
---
- hosts: all
 serial: 2  #每次只同时处理2个主机,将所有task执行完成后,再选下2个主机再执行所有task,直至所
有主机
 gather_facts: False
 tasks:
   - name: task one
 comand: hostname
   - name: task two
     command: hostname

九、委派至其它主机执行

利用委托技术,可以在非当前被控主机的其它主机上执行指定操作 范例: 将任务委派给指定的主机执行
[root@ansible ~]#cat delegate.yml 
#在10.0.0.8上执行hostname -I,而非当前主机localhost
- hosts: localhost
  
 tasks:
   - name: show ip address 
     command: hostname -I
     delegate_to: 10.0.0.8 #指定当前任务被委派给的目标主机
     delegate_facts: true #收集被委派的目标主机的facts信息

十、只执行一次

利用 run_once 指令可以只执行一次,而非在所有被控主机都执行
[root@ansible ~]#cat run_once.yml 
- hosts: websrvs
 tasks:
    - command: hostname
     run_once: true
[root@ansible ~]#ansible-playbook run_once.yml --list-hosts

十一、环境变量

临时修改环境变量
[root@ansible ~]#cat environment.yml
- hosts: localhost
 tasks:
    - shell: echo $PATH
     environment:
       PATH: /usr/local/app/bin:{{ ansible_env.PATH }}
[root@ansible ~]#ansible-playbook environment.yml -v

十二、Yaml 文件的相互调用

1、include
利用include 或 include_tasks 可以在某个task中调用其它的只有task内容的yaml文件
[root@ansible ansible]#cat a.yml 
---
- hosts: websrvs
  
 tasks:
   - name: run a job
     command: wall run a job
   - name: excute b.yml
     include: b.yml    #调用另一个yaml文件
      #include_tasks: b.yml #另一种写法
[root@ansible ansible]#cat b.yml 
- name: run b job
 command: wall run b job

2、import_playbook

还可以将多个包含完整内容的yml文件由一个yml统一调用
[root@ansible ansible]#cat main.yml 
- import_playbook: tasks1.yml
- import_playbook: tasks2.yml
[root@ansible ansible]#cat tasks1.yml

 

   

标签:tasks,name,nginx,ansible,第三十七,Template,root,yml,playbook
From: https://www.cnblogs.com/dujy/p/18097501

相关文章

  • WPF ErrorTemplate
    //xaml<Windowx:Class="WpfApp91.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF datagrid datagridtemplatecolumn DataGridTemplateColumn.CellEditingTemplate D
    //xaml<Windowx:Class="WpfApp89.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF TreeView HierarchicalDataTemplate
    //xaml<Windowx:Class="WpfApp87.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF CollectionViewSource GroupDescriptions GroupStyle ItemsPanelTemplate
    <Windowx:Class="WpfApp83.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......
  • WPF DataTemplate DataTrigger
    <Windowx:Class="WpfApp79.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......
  • WPF DataTemplate DataTemplateSelector
    //xaml<Windowx:Class="WpfApp78.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • WPF DataTemplate DataType
    //xaml<Windowx:Class="WpfApp77.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......
  • Go语言常用标准库——json、文件操作、template、依赖管理及Go_module使用
    文章目录Go语言之jsonMarshal函数Unmarshal函数Go语言之文件操作打开和关闭文件读取文件file.Read()基本使用循环读取bufio读取文件ioutil读取整个文件文件写入操作Write和WriteStringbufio.NewWriterioutil.WriteFile练习copyFile实现一个cat命令template模板模板示例依......
  • vllm 通过不同的chat_template推理部署常见qwen、chatglm、llama3等开源大模型
    vllm版本4.0.0镜像vllmgithub官方镜像gpuv10032ga80080gopenaiapi方式出现的问题通过chat-template聊天模板解决1推理部署qwen系列模型测试我是谁问题:回答内容含有分词符,回答有杂论冗余内容模型文件没有默认聊天模板vllm官方也没有聊天模板找不到不过......
  • wpf DataTemplate 动态模板内容
     <DataGridTemplateColumnWidth="50"Header="选择">              <DataGridTemplateColumn.CellTemplate>                <DataTemplate>                       ......