使用 Terraform 和 Kubernetes 部署时如何修改 Docker 容器中的文件? [英] How to modify a file in a Docker container when deploying with Terraform and Kubernetes?
问题描述
作为更大模块的一部分,我想部署一个 nginx
容器并替换其默认的 nginx.conf
.新配置应使用部署时生成的 Terraform resources 数据构建.有办法吗?
As a part of a bigger module, I want to deploy an nginx
container and replace its default nginx.conf
. The new config should be built using Terraform resources' data which is generated at the time of deployment. Is there a way to do it?
推荐答案
我设法按照以下步骤将标准的 nginx.conf 替换为动态生成的:
I managed to replace the standard nginx.conf with a dynamically generated one following these steps:
- 为动态数据创建一个带有占位符的模板配置文件
- 使用 Terraform 的
template_file
数据源 解析文件 - 将解析后的数据存储在 ConfigMap 中,并将映射挂载为 Nginx 容器的卷
一步一步:
创建名为nginx-conf.tpl的nginx.conf模板:
Create nginx.conf template named nginx-conf.tpl:
events {
worker_connections 4096; ## Default: 1024
}
http {
server {
listen 80;
listen [::]:80;
server_name ${server_name};
location /_plugin/kibana {
proxy_pass https://${elasticsearch_kibana_endpoint};
}
location / {
proxy_pass https://${elasticsearch_endpoint};
}
}
}
使用以下 Terraform 代码解析 nginx-conf.tpl 模板:
Parse the nginx-conf.tpl template with the following Terraform code:
data "template_file" "nginx" {
template = "${file("${path.module}/nginx-conf.tpl")}"
vars = {
elasticsearch_endpoint = "${aws_elasticsearch_domain.example-name.endpoint}"
elasticsearch_kibana_endpoint = "${aws_elasticsearch_domain.example-name.kibana_endpoint}"
server_name = "${var.server_name}"
}
}
创建一个 ConfigMap 并使用 nginx.conf
键将解析后的模板存储在那里:
Create a ConfigMap and store the parsed template there with nginx.conf
key:
resource "kubernetes_config_map" "nginx" {
metadata {
name = "nginx"
}
data = {
"nginx.conf" = data.template_file.nginx.rendered
}
}
最后,将 ConfigMap 键挂载为容器卷:
Finally, mount the ConfigMap key as a container volume:
# ...
spec {
# ...
container {
# ...
volume_mount {
name = "nginx-conf"
mount_path = "/etc/nginx"
}
}
volume {
name = "nginx-conf"
config_map {
name = "nginx"
items {
key = "nginx.conf"
path = "nginx.conf"
}
}
}
}
# ...
就是这样.Nginx 服务器将开始使用提供的配置.
That's it. Nginx server will start using the provided config.
有用的链接:Kubernetes ConfigMap as volume, Terraform Temple_file 数据源文档.
这篇关于使用 Terraform 和 Kubernetes 部署时如何修改 Docker 容器中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!