Search code examples
terraformterraform-provider-azureazure-rm

How to declare a azurerm_container_group resource that uses ports with different protocols?


I am trying to setup a stasd-exporter, which requires 2 types ports: a UDP and a TCP.

In the statsd-exporter's readme, the example uses 2 different types of ports:

docker pull prom/statsd-exporter

docker run -d -p 9102:9102 -p 9125:9125 -p 9125:9125/udp \
        -v $PWD/statsd_mapping.yml:/tmp/statsd_mapping.yml \
        prom/statsd-exporter --statsd.mapping-config=/tmp/statsd_mapping.yml

The tutorial I am following uses 8125 for UDP and 9102 for TCP.

Figured out that I can use a list of ports, but I could not find how to use set each ports protocol inside ports block

For now, what I have in the azurerm_container_group is:

resource "azurerm_container_group" "statsd_exporter" {
  name                = "${azurerm_resource_group.monitoring.name}-common"
  location            = azurerm_resource_group.monitoring.location
  resource_group_name = azurerm_resource_group.monitoring.name

  ip_address_type = "public"
  os_type         = "Linux"

  container {
    name                  = "statsd-exporter"
    image                 = "prom/statsd-exporter"
    cpu                   = "0.5"
    memory                = "1"
    environment_variables = ""

    commands = [
      "/bin/bash", "-c", "--statsd.listen-udp=:8125", "--web.listen-address=:9102"
    ]

    ports {
        port     = [8125, 9102] # --> 8125 should be UDP and 9102 should be TCP
        protocol = ## < < ??? > > ##
    }

  }

How to associate each port of a azurerm_container_group's container to a different protocol?


Solution

  • You can define the ports as below:

    resource "azurerm_container_group" "statsd_exporter" {
      name                = "statsd"
      location            = azurerm_resource_group.example.location
      resource_group_name = azurerm_resource_group.example.name
      ip_address_type = "public"
      os_type         = "Linux"
    
      container {
        name                  = "statsd-exporter"
        image                 = "prom/statsd-exporter"
        cpu                   = "0.5"
        memory                = "1"
        commands = [
          "/bin/bash", "-c", "--statsd.listen-udp=:8125", "--web.listen-address=:9102"
        ]
        ports {
          port     = 9102
          protocol = "TCP"
        }
        ports{
        port =  8125
        protocol = "UDP"
        }
      }
    }
    

    Output:

    Doing a terraform plan:

    enter image description here

    Terraform apply:

    enter image description here

    In Azure Portal:

    enter image description here

    Reference:

    azurerm_container_group | Resources | hashicorp/azurerm | Terraform Registry