使用Terraform和Kubernetes进行部署时如何在Docker容器中修改文件? [英] How to modify a file in a Docker container when deploying with Terraform and Kubernetes?

查看:128
本文介绍了使用Terraform和Kubernetes进行部署时如何在Docker容器中修改文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为更大模块的一部分,我想部署一个 nginx 容器并替换其默认的 nginx.conf 。新配置应使用在部署时生成的Terraform 资源’数据构建。有办法吗?

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替换了标准nginx.conf。 :

I managed to replace the standard nginx.conf with a dynamically generated one following these steps:


  1. 使用动态数据占位符创建模板配置文件

  2. 使用Terraform的 template_file 数据源

  3. 将已解析的数据存储在ConfigMap中,并将映射安装为Nginx容器的卷

  1. Create a template config file with placeholders for dynamic data
  2. Parse the file using Terraform's template_file data source
  3. Store the parsed data in a ConfigMap and mount the map as a volume for the Nginx container

分步:

创建名为 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};
    }
  }
}

解析 nginx-conf.tpl 模板,其中包含以下Terraform代码:

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作为卷 Terraform temple_file数据源文档

这篇关于使用Terraform和Kubernetes进行部署时如何在Docker容器中修改文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆