Anthony Kong
Anthony Kong

Reputation: 40624

How to set a variable in a chef template?

In the official document, there is only one use case of variable for template: the caller has to pass in a hash.

However for me I have a very simple use case. I only want to set a server name in a sensu client configuration template file client.json.erb

Here is the template file:

{
  "client": {
    "name": "<%= @server_name %>",
    "address": "<%= node.ipaddress %>",
    "keepalive": {
      "thresholds": {
        "warning": 90,
        "critical": 180
      }
    },
    "subscriptions": [ "default" ]
  }
}

It is my chef code:

server_name = "server1.example.com"

template "/etc/sensu/conf.d/client.json" do
  variables({
    :server_name => server_name
  })
  source "sensu-template/conf.d/client.json.erb"
end

The config file turns out to become:

{
  "client": {
    "name": "{}",
    "address": "10.0.1.1",
    "keepalive": {
      "thresholds": {
        "warning": 90,
        "critical": 180
      }
    },
    "subscriptions": [ "default" ]
  }
}

How should I pass a variable name properly into the template?

Upvotes: 2

Views: 18468

Answers (1)

Anthony Kong
Anthony Kong

Reputation: 40624

This fixed my problem:

template "/etc/sensu/conf.d/client.json" do
  variables(
    'server_name': server_name
  )
  source "sensu-template/conf.d/client.json.erb"
end

Upvotes: 10

Related Questions