saltstack在jianja模板中,执行salt函数来获取某些变量的值,并且将配置写入到配置文件中?

问题描述

  通过saltstack的jinja模板方式,可以将变量的值写入到配置文件,即动态获取的方式。这里介绍,通过执行salt函数来获取值的方式。

演示

1.通过在sls中,增加jinja的模板信息,变量信息,通过salt函数获取该值。

apache-config:
  file.managed:
    - name: /etc/httpd/conf/httpd.conf
    - source: salt://lamp/files/httpd.conf
    - user: root
    - group: root
    - mode: 644
    - template: jinja
    - defaults:
      Listen_Port: 86
      OS: {{ grains['os'] }}
      HW_ADDR: {{ salt['network.hw_addr']('eth1') }}  

 

2.修改配置文件httpd.conf,增加引用变量HW_ADDR

# Hard Addr is {{ HW_ADDR }}   #应用变量的值。

 

3.执行状态模块,进行配置

[root@testvm01 lamp]# salt 'testvm03' state.sls lamp.lamp
testvm03:
----------
          ID: lamp-pkgs
    Function: pkg.installed
      Result: True
     Comment: All specified packages are already installed
     Started: 17:08:54.896384
    Duration: 484.232 ms
     Changes:   
----------
          ID: apache-config
    Function: file.managed
        Name: /etc/httpd/conf/httpd.conf
      Result: True
     Comment: File /etc/httpd/conf/httpd.conf updated
     Started: 17:08:55.383683
    Duration: 67.694 ms
     Changes:   
              ----------
              diff:
                  --- 
                  +++ 
                  @@ -7,7 +7,7 @@
                   # for a discussion of each configuration directive.
                   #
                   # OS is RedHat
                  -# Hard Addr is 08:00:27:7c:9c:2d
                  +# Hard Addr is 08:00:27:f1:2e:e9  #获取到了网卡的信息,并且增加到该配置文件中
                   # Do NOT simply read the instructions in here without understanding
                   # what they do.  They're here only as hints or reminders.  If you are unsure
                   # consult the online docs. You have been warned.  
----------
          ID: php-config
    Function: file.managed
        Name: /etc/php.ini
      Result: True
     Comment: File /etc/php.ini is in the correct state
     Started: 17:08:55.451548
    Duration: 11.319 ms
     Changes:   
----------
          ID: apache-service
    Function: service.running    #检测到配置文件发生了变化,就reload配置文件
        Name: httpd
      Result: True
     Comment: Service reloaded
     Started: 17:08:55.498927
    Duration: 82.003 ms
     Changes:   
              ----------
              httpd:
                  True
----------
          ID: mysql-service
    Function: service.running
        Name: mysqld
      Result: True
     Comment: The service mysqld is already running
     Started: 17:08:55.581261
    Duration: 106.275 ms
     Changes:   

Summary for testvm03
------------
Succeeded: 5 (changed=2)
Failed:    0
------------
Total states run:     5
Total run time: 751.523 ms

 

jinja中调用salt函数的语法:

# The following two function calls are equivalent.
{{ salt['cmd.run']('whoami') }}
{{ salt.cmd.run('whoami') }}

注意:第一中写法,参数要有括号,并且用单引号,否则会报错。

 

文档创建时间:2019年3月11日17:10:01

posted @ 2019-03-11 17:14  Zhai_David  阅读(1005)  评论(0编辑  收藏  举报