1

我正在使用 ansible 安装 Apache,目前我httpd.conf在 ansible 存储库中有多个文件(test/dev/staging/production),除了一些特定于环境的设置外,大部分内容都是相同的。

是否可以使用一个httpd.conf模板文件,并在发送httpd.conf到远程服务器时修改文件?

4

1 回答 1

3

是的你可以。使用 jinja2 和 group_vars。

因此,您在模板/文件夹中所做的操作会创建如下文件:

templates/http.conf.j2

假设你有这样的东西:

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName {{ subdomain }}.{{ domain }}
    ServerAlias www.{{ subdomain }}.{{ domain }}
</VirtualHost>

您的布局应如下所示:

├── group_vars
│   ├── all
│   │   └── config
│   ├── dev
│   │   └── config
│   └── test
│       └── config
├── inventory
│   ├── dev
│   │   └── hosts
│   └── test
│       └── hosts
├── site.yml
└── templates
    └── http.conf.j2

group_vars/all你会有domain: "example.com"

group_vars/dev你会有subdomain: dev

group_vars/test你会有subdomain: test

在您的任务中,您将拥有 ansible 模板命令,即

- hosts: all
  tasks:
    - name: Copy http conf
        template:
        dest: /etc/apache2/http.conf
        src: templates/http.conf.j2
        owner: root
        group: root

像这样运行你的剧本:

ansible-playbook -i inventory/test site.yml

该文件应最终出现在主机上,如下所示:

<VirtualHost *:80>
    ServerName test.example.com
    ServerAlias www.test.example.com
</VirtualHost>
于 2017-09-27T02:06:17.007 回答