需求描述:
在使用saltstack的时候,有的时候,需要根据不同的变量来增加配置,比如,bind,监听端口,这些都可以通过变量写入,并且在配置的时候引用,下面是一个例子,用来演示,如何使用jinja模板,在state模块中使用。
演示:
1.编写sls及saltstack的状态文件
lamp-pkgs:
pkg.installed:
- pkgs:
- httpd
- php
- mysql
- mysql-server
- php-mysql
- php-cli
- php-mbstring
apache-config:
file.managed:
- name: /etc/httpd/conf/httpd.conf
- source: salt://lamp/files/httpd.conf
- user: root
- group: root
- mode: 644
php-config:
file.managed:
- name: /etc/php.ini
- source: salt://lamp/files/php.ini
- user: root
- group: root
- mode: 644
apache-service:
service.running:
- name: httpd
- enable: True
- reload: True
- watch: #监控,如果httpd的配置文件发生了变化,那么就对httpd服务进行reload操作。
- file: apache-config
mysql-service:
service.running:
- name: mysqld
- enable: True
- reload: True
备注:该sls状态文件的主要作用就是,安装LAMP的环境,并且启动具体的服务。
2.将httpd的配置文件作为模板文件,sls中写入变量
apache-config: file.managed: - name: /etc/httpd/conf/httpd.conf - source: salt://lamp/files/httpd.conf - user: root - group: root - mode: 644 - template: jinja #将httpd.confg文件作为jinja模板文件 - defaults: Listen_Port: 89 #指定具体的变量,也就是参数,也可以指定多个,在下一行
3.修改原配置文件httpd.conf,加入引用变量
[root@testvm01 lamp]# vi files/httpd.conf #对以下的文件进行修改。 #Listen 12.34.56.78:80 Listen {{ Listen_Port }}
备注:这里的意思,就是配置文件httpd.conf会引用lamp.sls文件中列出的变量值
4.通过state模块,进行配置
[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: 16:14:17.055138
Duration: 483.099 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: 16:14:17.541277
Duration: 66.713 ms
Changes:
----------
diff:
---
+++
@@ -133,7 +133,7 @@
# prevent Apache from glomming onto all bound IP addresses (0.0.0.0)
#
#Listen 12.34.56.78:80
-Listen 87 #diff命令,检测到监听端口的变化
+Listen 89
#
# Dynamic Shared Object (DSO) Support
----------
ID: php-config
Function: file.managed
Name: /etc/php.ini
Result: True
Comment: File /etc/php.ini is in the correct state
Started: 16:14:17.608216
Duration: 11.019 ms
Changes:
----------
ID: apache-service
Function: service.running
Name: httpd
Result: True
Comment: Service reloaded #检测到配置文件发生变化之后,进行了reload操作
Started: 16:14:17.653648
Duration: 81.143 ms
Changes:
----------
httpd:
True
----------
ID: mysql-service
Function: service.running
Name: mysqld
Result: True
Comment: The service mysqld is already running
Started: 16:14:17.735066
Duration: 96.421 ms
Changes:
Summary for testvm03
------------
Succeeded: 5 (changed=2)
Failed: 0
------------
Total states run: 5
Total run time: 738.395 ms
5.检查testvm03主机上的配置文件的状态和服务状态
[root@testvm03 ~]# grep ^Listen /etc/httpd/conf/httpd.conf
Listen 89
[root@testvm03 ~]# service httpd status
httpd (pid 1139) is running...
[root@testvm03 ~]# netstat -ntlp | grep httpd
tcp 0 0 :::89 :::* LISTEN 1139/httpd
备注:发现配置文件已经修改过来了,并且配置文件也进行了重新加载。达到了,通过引用变量的方法获取变量值来修改配置的方法,httpd.conf中不在是固定的写法,而是通过变量的值来获取某个值。
文档创建时间:2019年3月11日16:18:17