9-saltstack(5)_通过Jinja2模块以及Grain和Pillar扩展主机状态_二

用Jinja2配合Grains和Pillar动态下发配置文件

  • 简单级别下发模板的实现

简单下发:

## vim /srv/salt/template.sls
template_test:
  file.managed:
    - source: salt://test.j2
    - name: /tmp/test.conf
    - user: root
    - group: root
    - mode: 644
    - template: jinja

## vim /srv/salt/test.j2
cpu_num= {{ grains['num_cpus'] }}
mem_total = {{ grains['mem_total'] }}
hostname = {{ grains['host'] }}
user = {{ pillar['user'][0] }}              ======> 此处取user的第一个值,user值参照上一篇

## salt 192.168.184.133 state.sls template

## salt 192.168.184.133 cmd.run "cat /tmp/test.conf"
192.168.184.133:
    cpu_num= 1
    mem_total = 981
    hostname = localhost
    user = user01

在上述模板的基础上,实现简单的Jinja2配合Grains和Pillar动态下发配置文件

## vim /srv/salt/test.j2
{% if grains['num_cpus'] <= 8 %}
cpu_num= {{ grains['num_cpus'] }}
{% endif %}
{% if grains['mem_total'] <= 512 %}
mem_total <= 512
{% elif grains['mem_total'] >= 1024 %}
mem_total >= 1024
{% endif %}
hostname = {{ grains['host'] }}
{% for i in pillar['user'] %}
{{ i }}
{% endfor %}

## salt 192.168.184.133 cmd.run "cat /tmp/test.conf"
192.168.184.133:
    
    cpu_num= 1
    
    
    hostname = localhost
    
    user01
    
    user02
    
    user03
  • 实现sshd动态白名单部署
## vim /srv/salt/sshd.sls
ssh:
  pkg:
    - installed
    - name: openssh-server  ##如果分段写,那么要用 - names
                            ##                       - openssh-server 
  service.running:
    - name: sshd            ## 可改为  sshd:
    - enable: True          ##             - enable: True
    - watch:                ##             - watch:
      - file: ssh           ##               - file: sshd
      - pkg: ssh            ##               - pkg: sshd
  file.managed:
    - name: /etc/ssh/sshd_config
    - source: salt://sshd_config
    - template: jinja
                                  ## 在没有指定pkg和file的- name选项时,默认- name用最开始的ID,也就是ssh
## cat /srv/salt/sshd_conf         ====>在前面加上jinja即可,即AllowUsers user01 user02 user03……
{% if pillar['user'] %}
{% for i in pillar['user'] %}
AllowUsers {{ i }}
{% endfor %}
{% endif %}
  • 批量部署Nginx代理服务器

你可能感兴趣的:(9-saltstack(5)_通过Jinja2模块以及Grain和Pillar扩展主机状态_二)