ansible 模板

文件传输时,出现了格式一致,内容不一致的动态配置文件时,模板就可以大显神威了,现有的file copy command 模块都无法直接满足这个需求

基本规则

  • 模板专用目录:跟 playbook 同目录下创建一个template目录
  • 基准配置文件:基准配置文件放在 template 目录下,文件后缀必须是 *.j2
  • 自动替换数据:通过 jinja2 模板语言将数据传输到基准配置文件中

快速入门

实践需求

部署nginx时,基于基准的nginx配置文件,自动生成专用的nginx配置文件,改造服务端口

文件配置

  • /etc/ansible/hosts
[web]
192.168.8.14 nginx_port=81
192.168.8.15 nginx_port=82
192.168.8.16 nginx_port=83
  • template/nginx.conf.j2

关键点在 {{ nginx_port }}

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       {{ nginx_port }} default_server;
        listen       [::]:{{ nginx_port }} default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}
  • nginx.yaml

template 模块 替换 copy 模块

---
# 使用 template 拷贝文件
- hosts: web
  remote_user: root
  tasks:
    - name: copy config
      # copy: src=nginx.conf dest=/etc/nginx/nginx.conf
      template: src=./template/nginx.conf.j2 dest=/etc/nginx/nginx.conf
      # 通知 重启 处理
      notify: 
        - restart nginx
  handlers:
    # 重启
    - name: restart nginx
      service: name=nginx status=restarted

执行

ansible-playbook -C nginx.yaml
ansible-playbook nginx.yaml

模板语言

jinja2 的模板语言,没有什么新颖的东西,这里权当复习

  • {{ }} 用于表达式,比如变量,表达式等
  • {% %} 用于控制语句,比如if for 等
  • {# #} 用于注释

流程控制就是学习 {% %} 的用法

流程控制语句

条件控制语句
  • {% if 条件 %} 执行语句 {% endif %}

例:{% if 变量 is defined %}

循环语句
  • {% for 条件 %} 执行语句 {% endfor %}

例:{% for 变量 in 变量列表 %}

if 流程

  • 主机清单
[web]
127.0.0.1 port=81 name=a
127.0.0.2 port=82 name=b
127.0.0.3 port=83 name=c
  • nginx 配置模板
server {
    {% if port is defined %}
    listen {{ port }}
    {% endif %}
    
    {% if name is defined %}
    server_name {{ name }}
    {% endif %}

    location / {
    }
}
  • playbook
- host: web
  remote_user: root
  tasks:
    - name: template config
      template: src=templates/nginx.conf.j2 dest=/tmp/nginx.conf

for 流程

  • 主机清单
[web]
127.0.0.1
127.0.0.2
127.0.0.3
  • playbook
---
- host: web
  remote_user: root
  vars:
    nginx_vhosts:
      - vhost1:
        port: 81
        name: a
      - vhost2:
        port: 82
      - vhost3:
        name: b
  tasks:
    - name: template config
      template: src=templates/nginx.conf.j2 dest=/tmp/nginx.conf
  • nginx.conf.j2
{% for vhost in nginx_vhosts %}
server {
    {% if vhost.port is defined %}
    listen {{ vhost.port }}
    {% endif %}
    
    {% if vhost.name is defined %}
    server_name {{ vhost.name }}
    {% endif %}

    location / {
    }
}
{% endfor %}

item with_items

---
- hosts: web
  remote_user: root
  tasks:
    - name: add serveal users
      user: name={{ item }} state=present groups=wheel
      with_items:
        - username1
        - username2

多值迭代

---
- hosts: web
  remote_user: root
  tasks:
    - name: add serveal users
      user: name={{ item.name }} group={{ item.group }} state=present groups=wheel
      with_items:
        - { name: 'user1', group: 'group1' }
        - { name: 'user2', group: 'group2' }
        - { name: 'user3', group: 'group3' }

playbook 中可以使用 when 语句做条件判断,模板中可以使用 jinja2 判断语法做条件判断

when 语句

示例

---
- hosts: web
  remote_user: root
  tasks: 
    - name: install package
      yum: name=nginx state=present
      when: ansible_os_family == "RedHat"
  • 位置: task 下面的一条配置项

  • 格式: when: 条件对象 判断操作符 判断值

  • 内容: when 语句中 条件变量可以是 变量、Facts、命令结果等

  • 判断: 支持以下几种类型

    算数运算符 +,-,/,//,%,*等

    比较操作 ==, !=, >=, <=, >, < 等

    逻辑运算 and,not,or

playbook

示例

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes {{ ansible_processor_vcpus + 2 }};
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       {{ nginx_port }} default_server;
        listen       [::]:{{ nginx_port }} default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值