Variables can be used in an Asterisk dialplan to help reduce typing, add clarity, or add additional logic to a dialplan. If you have some computer programming experience, you probably already understand what a variable is. If not, don't worry; we'll explain what variables are and how they are used.
You can think of a variable as a container that can hold one value
at a time. So, for example, we might create a variable called JOHN and assign it the value of Zap/1. This way, when we're writing our
dialplan, we can refer to John's channel by name, instead of remembering
that John is using the channel named Zap/1.
There are two ways to reference a variable. To reference the
variable's name, simply type the name of the variable, such as JOHN. If, on the other hand, you want to
reference its value, you must type a dollar sign, an opening curly
brace, the name of the variable, and a closing curly brace. Here's how
we'd reference the variable inside the Dial() application:
exten => 555,1,Dial(${JOHN})
In our dialplan, whenever we write ${JOHN}, Asterisk will automatically replace
it with whatever value has been assigned to the variable named JOHN.
There are three types of variables we can use in our dialplan: global variables , channel variables , and environment variables. Let's take a moment to look at each type.
As their name implies, global variables
apply to all extensions in all contexts. Global variables are useful
in that they can be used anywhere within a dialplan to increase
readability and manageability. Suppose for a moment that you had a
large dialplan and several hundred references to the Zap/1 channel. Now imagine you had to go
through your dialplan and change all those references to Zap/2. It would be a long and error-prone
process, to say the least.
On the other hand, if you had defined a global variable with the
value Zap/1 at the beginning of
your dialplan and then referenced that instead, you would only have to
change one line.
Global variables should be declared in the [globals] context at the beginning of the
extensions.conf file. They can also be defined
programmatically, using the GLOBAL() dialplan function[80]. Here is an example of how both methods look inside of a
dialplan. The first shows setting a global variable named JOHN with a value of Zap/1. This variable is set at the time
Asterisk parses the dialplan. The second example shows how a global
varible can be set in the dialplan. In this case, the variable named
George is being assigned the value
of SIP/George when extension 124 is
dialed in the [employees]context>.
[globals]
JOHN=Zap/1
[employees]
exten => 124,1,Set(GLOBAL(GEORGE)=SIP/George)