# Macros: Creation and Usage

> Chapter 8 of the Courseiva SPLUNK-CORE-CERTIFIED-POWER-USER curriculum — https://courseiva.com/learn/splunk-core-certified-power-user/macros-creation-and-usage

**Official objective:** 3.1 — Create and manage search macros to simplify and standardize searches.

## Introduction

A search macro is a saved snippet of Splunk search language that you can reuse in multiple searches. It solves the problem of repeating the same complex filter, calculation, or transformation over and over, turning a long, error-prone string into a short, memorable name. For the SPLK-1003 exam, you must understand how to create, manage, and use macros, because they are a core tool for standardising searches and making them easier to maintain.

## The Family Recipe Card Box Analogy

A family recipe card box is a collection of index cards, each holding a specific recipe.

When you cook a dish that your family loves, you don't write down every single step from scratch every time. Instead, you have a card that says 'Grandma's Tomato Sauce'. That card represents a series of steps: chop three onions, fry them in olive oil, add a tin of chopped tomatoes, simmer for twenty minutes, add basil. Every time you want that sauce, you pull out the card, follow it, and you get a consistent result. You don't need to remember the ingredients or the timings each time.

Now, imagine you want to make a larger batch. You can write a new card that says 'Double Grandma's Sauce'. That new card references the original but adds a note: 'double everything'. You can also create a card called 'Spicy Grandma's Sauce' that says: follow the original, but add two chopped chillies. These new cards are like variations on a theme.

In Splunk, a macro works exactly like one of those recipe cards. Instead of typing out the entire search string every time you need to filter for login failures from a specific set of users, you save that search snippet as a macro and just call it by name. The macro expands into the full search text whenever you use it. It keeps your searches clean, consistent, and easy to update. If the recipe changes (like the IP addresses of the users changes), you only update the macro card, not every single search that uses it.

## Core explanation

A search macro is a stored piece of a Splunk search that you can insert into another search by using its name, plus a dollar sign and backticks.

Here is exactly how it works. Think of a macro as a kind of search template. You define it with a name, like 'failed_logins', and you specify the search text it represents, such as 'index=security sourcetype=linux_secure "Failed password"'. When you type \`$failed_logins$\` into any search bar, Splunk replaces \`$failed_logins$\` with the full text 'index=security sourcetype=linux_secure "Failed password"'. The search then runs exactly as if you had typed that full text.

Why does this matter? First, consistency. If you have ten team members searching for failed logins, without a macro, someone might type 'index=security failed password', another might type 'sourcetype=linux_secure error', and so on. With a macro, every search starts from an identical, reviewed base string. Second, maintainability. If the security team renames the source type from 'linux_secure' to 'linux_auth_log', you update the macro definition once, and every search that uses that macro instantly uses the new source type. Without a macro, you would need to edit every saved search, dashboard panel, and ad-hoc query.

A macro can also accept arguments, or 'parameters'. Imagine a macro called 'user_activity' defined as 'index=main sourcetype=access_combined user=$user$'. When you call it with \`$user_activity("jsmith")$\`, Splunk replaces $user$ with 'jsmith'. This makes macros even more flexible — you can reuse the same search logic but change the specific value that is searched for.

Macros are stored in the Splunk knowledge object system. You create them through the Settings menu, then Knowledge, then Search macros. When you define a macro, you give it: a unique name, the search string it expands to, whether it accepts arguments, and optionally validation (like a regex pattern the argument must match) and a description.

A macro can contain any valid part of a search: a full base search, a filtering command like \`search error\`, an eval expression, a stats function, or even a subsearch. However, the entire macro must expand to something syntactically valid within the context where you use it. For example, if your macro expands to 'error | stats count by host', you cannot use it inside a \`search\` command, because that would create an invalid search like 'search error | stats count by host' — you would need to use it as the entire search or at a pipeline point.

Macros also have an important behaviour: they are evaluated at parse time, not at run time. This means Splunk expands the macro text into the search before it starts to process any events. This is different from a search-time eval or lookup. It also means you cannot change the macro definition dynamically within a search.

Crucially, you can nest macros: a macro can call another macro. For instance, macro A expands to 'index=main sourcetype=access_combined | search $macroB$', and macro B expands to 'status>400'. Using \`$A$\` would produce 'index=main sourcetype=access_combined | search status>400'. Nesting must be done carefully to avoid circular references (A calls B which calls A), which Splunk will reject.

Macros are also scoped to apps. When you create a macro, it belongs to a specific app (like 'search' or a custom app). Only users with access to that app can use the macro. You can also set permissions on a macro: private to you, or shared with everyone in the app.

In summary, a macro is a search snippet you name and reuse. It reduces typing errors, enforces standards, makes updates easier, and with arguments, it becomes a tiny, flexible search function. For the exam, you must know the syntax \`$macroname$\` (with two dollar signs and backticks) for macros without arguments, and \`$macroname("argument")$\` for those with arguments. You must also know that macros are edited in Settings > Knowledge > Search macros.

## Real-world context

An IT administrator at a medium-sized company, Maria, is responsible for monitoring a fleet of 200 servers running Linux and Windows. Her team gets daily requests like 'show me all SSH login attempts from external IPs for the last hour'. The typical search looks like: 'index=os sourcetype=linux_secure ("Accepted" OR "Failed") ssh | where NOT src_ip=10.0.0.0/8 | table _time host user src_ip auth_action'. That is a long, complex string.

Maria creates a macro called 'ssh_external' without arguments. She defines it exactly as that entire search string. Now, any team member can type \`$ssh_external$ | ...\` and immediately get the filtered results. This eliminates typos and ensures everyone is looking at the same data in the same way.

Next, her manager asks for a weekly report of all failed logins across all systems. Instead of creating a static search, Maria creates a macro called 'failed_logins' that only contains 'index=os (Failed OR failure OR "Authentication failure")'. She does not fix the time range in the macro because time range is set per search. She also creates a second macro called 'top_failed_users' that expands to the stats part: '| stats count by user, host'. With these two macros, the weekly report search becomes: \`$failed_logins$ | $top_failed_users$ | where count > 5 | sort - count\`. This is now readable, reusable, and easy to change.

A more advanced scenario: The development team wants to track errors by application version. Maria creates a macro with an argument: 'app_errors' defined as 'index=app sourcetype=app_log app_name="$app$" level=error'. To use it, she types \`$app_errors("inventory")$\`. The team can now quickly check errors for any app by changing just the argument.

One day, the infrastructure team decides to rename the Linux authentication source type from 'linux_secure' to 'linux_auth'. Without macros, Maria would need to update every dashboard, every saved search, every alert. With macros, she opens Settings > Knowledge > Search macros, finds 'failed_logins', changes the source type string, and saves. Every dashboard and alert that uses \`$failed_logins$\$ automatically switches to the new source type.

Maria also uses macros to enforce security standards. Her company requires every search that touches production data to include a filter excluding certain internal IP ranges. She creates a macro called 'prod_safe' that expands to 'index=production NOT (src=10.0.0.0/8 OR dst=10.0.0.0/8)'. This macro is shared with the entire team, and she instructs everyone to always begin production searches with \`$prod_safe$ | ...\`. This simple practice ensures no accidental exposure of sensitive internal data in reports.

In a real environment, a macro might also include a time modifier. For example, 'last_3_hours' defined as 'earliest=-3h@h latest=@h'. Using \`$last_3_hours$\` in a search sets the time range to the last three full hours, ensuring consistency across scheduled reports.

Finally, Maria uses the 'Show arguments' option when defining a macro to allow more than one argument. For instance, a macro 'two_field_filter' defined as 'index=$idx$ sourcetype=$st$' can be called with \`$two_field_filter("main", "access_combined")$\`. The arguments are passed in order, so the first argument fills $idx$ and the second fills $st$. This is powerful but requires careful documentation so users know the correct order.

## Exam focus

The SPLK-1003 exam tests your understanding of search macros directly in the 'Knowledge Objects' domain. Expect around 3-5 questions related to macros in the exam, covering creation, usage, arguments, and permissions.

The most common question type gives you a scenario where a team needs to reuse a specific search filter across multiple searches, and asks which knowledge object you would create. The correct answer is almost always 'a search macro'. The traps include answers like 'saved search' (which saves a search for later execution, not for reuse as a snippet), 'field extraction' (which parses data, not the same thing), or 'lookup' (which maps values). You need to recognise that a macro is specifically for reusing a portion of SPL.

Another common question presents a macro definition and asks you to identify the correct syntax to call it. For example, a macro named 'filter_errors' with one argument. The correct call will be \`$filter_errors("critical")$\$. Wrong answers might use incorrect punctuation like single dollar signs, parentheses without escaping, or no argument when one is defined.

A frequent trap revolves around the concept of macros with arguments versus without. The exam loves to present a macro defined with arguments and ask what happens if you call it without providing the argument. The correct answer is that the search will fail at parse time because the parameter is unresolved. Similarly, they might present a macro without arguments called with parentheses and an argument — that also results in an error.

Another trap: macro nesting. You might be given macro A that calls macro B, and macro B has an error (like a typo in a sourcetype). The question asks what happens when you search with \`$A$\$. The correct answer is that the search fails at parse time because B's error becomes part of A. Traps include 'the search runs but returns no results' or 'it fails at search time'. It fails at parse time because macros are expanded before the search runs.

Permissions: You will be asked about the scope of macros. A macro created in one app (like 'search') is not available in another app unless it is explicitly shared. The exam tests that a macro must be enabled and visible to the user's app. A common trap: thinking macros are global across all apps by default. They are not.

Validation patterns: When a macro is defined with argument validation (a regex), the exam may ask what happens if the submitted argument does not match the regex. Answer: Splunk will not accept the definition at create time if the argument fails the regex, but at call time, if the argument doesn't match, the search fails.

Key facts to memorise: 

- Macro syntax without arguments: \`$macroname$\$ 
- Macro syntax with arguments: \`$macroname("value")$\$ 
- Macros are edited in Settings > Knowledge > Search macros. 
- Macros expand at parse time. 
- Macros belong to an app. 
- You can nest macros but must avoid circular references. 
- Macros can contain any valid SPL fragment. 
- Deletion of a macro causes any search that references it to fail at parse time. 
- Macro names are case-sensitive. 
- The description field is optional but strongly recommended for documentation. 
- Use the 'Erase' button to delete a macro definition entirely. 

The exam may also test use of macros in dashboards. In a dashboard XML panel, a macro is referenced as \`$macroname$\$ or \`$macroname("arg")$\$. Ensure you understand that macros in dashboards behave identically to macros in the search bar.

Finally, the exam might ask about the difference between a macro and an eval function like 'tonumber'. They are not the same: a macro is a user-defined reusable snippet, while eval functions are built-in calculations. A macro can contain eval functions, but the macro is not a function itself.

## Step by step

1. **Navigate to the Search macros page** — Go to Settings > Knowledge > Search macros. This is the central location where you create, edit, and delete all macros. You must have appropriate permissions (admin or power user role with knowledge object editing rights) to access this page.
2. **Click New Search Macro** — Click the 'New' button to create a fresh macro. This opens a form where you specify the name, definition, and optional settings. The name must be unique within your app, and it should be descriptive enough to remind you what the macro does.
3. **Define the macro's destination app** — Choose the app (like 'search' or your custom app) where the macro will live. Macros are app-specific. If you choose the wrong app, users in other apps will not see it unless you export it or use global permissions. For the exam, remember that the 'search' app is the default.
4. **Enter the macro name and definition** — Type the name (no spaces, use underscores). In the 'Definition' field, enter the exact SPL snippet. This can be a simple filter like 'index=main status=404' or a complex pipeline. If the macro uses arguments, place $arg$ placeholders in the definition where the argument values should go.
5. **Configure arguments and validation (optional)** — If your macro uses arguments, check 'Show arguments'. A new section appears where you define the argument names (e.g., 'user', 'status'). You can also add a regex pattern to validate the argument value, which prevents invalid inputs. If validation fails, the macro will not be created.
6. **Set permissions and save** — By default, the macro is private to you. Click 'Permissions' to share it with 'Everyone' in the app, or keep it private. Save the macro. Once saved, it is immediately available in any search within the app, for the users who have access.
7. **Test the macro in a search** — In the Search app, type \`$your_macro_name$\$ (use backticks around the name) and run the search. For macros with arguments, type \`$your_macro_name("value")$\$. Verify the results match what you would get by typing the full SPL manually.

## Comparisons

### Search Macro vs Saved Search

**Search Macro:**
- A reusable snippet of SPL that is expanded at parse time
- Cannot run independently; must be part of a larger search
- Does not have a schedule or alerting actions

**Saved Search:**
- A complete search stored with a name and schedule
- Can run on a schedule and trigger alerts, emails, or scripting actions
- Usually set to run periodically or on demand as a report

### Macro Without Argument vs Macro With Argument

**Macro Without Argument:**
- No placeholder variables in the definition
- Called using `$macroname$` (empty parentheses not allowed)
- Fixed result: every call produces the exact same snippet

**Macro With Argument:**
- Has placeholder variables (e.g., $user$) in the definition
- Called using `$macroname("value")$` with a quoted argument
- Dynamic result: argument changes the expanded snippet

### Macro vs Field Extraction (regex)

**Macro:**
- Used to insert SPL into searches
- Expands at parse time
- Edited in Settings > Knowledge > Search macros

**Field Extraction (regex):**
- Used to extract structured fields from raw event data
- Applied at index time or search time
- Configured in Settings > Fields > Field extractions or props.conf

### Macro vs Lookup (CSV or KV Store)

**Macro:**
- Inserts SPL text into a search
- Stored as a definition in the knowledge object system
- Cannot be used to map values onto search results directly

**Lookup (CSV or KV Store):**
- Maps values from a static file or key-value store to search results
- Stored as a CSV file or KV store collection
- Used with the | lookup command to enrich events with extra fields

## Diagram

_Flowchart showing how a macro is expanded at parse time before the search is submitted to the indexers._

```mermaid
flowchart TD
    A[User writes search] --> B{Contains macro?}
    B -- Yes --> C[Parse-time expansion]
    C --> D[Macro definition fetched from Knowledge]
    D --> E[Macro text inserted into search]
    E --> F[Full search sent to search head]
    B -- No --> F
    F --> G[Search executes on indexers]
    G --> H[Results returned

    style A fill:#e0f7fa
    style C fill:#ffe0b2
    style E fill:#c8e6c9
    style G fill:#f3e5f5
```

## Common misconceptions

- **Misconception:** A macro is the same as a saved search. **Reality:** A macro is a reusable snippet of a search, not a saved search that runs on a schedule. A saved search is a complete search with a schedule and actions; a macro is just a search fragment you insert into other searches. (Both involve saving something in Splunk, and both are managed under Knowledge objects, so beginners often mix them up. The exam specifically tests distinguishing them.)
- **Misconception:** You can use a macro anywhere in a search, including inside a subsearch or inside an eval statement, without any restrictions. **Reality:** A macro must expand to syntactically valid SPL in the exact position where you insert it. If you use a macro that expands to 'stats count' inside a search command, it will break. Also, macros cannot be used inside eval strings because eval uses double quotes. (Macros look like variables and beginners think they are flexible like variables in programming languages. But SPL has strict syntax rules about where commands and arguments can go.)
- **Misconception:** If you create a macro and later change its definition, all searches that used the old definition will stop working until you update them manually. **Reality:** Changing a macro's definition automatically updates every search that references it, because the macro is expanded at parse time using the current definition. You do not need to touch the individual searches. (People think of macros as static copies. In reality, the macro is a reference that always resolves to the latest definition.)
- **Misconception:** Macros can only contain search terms (like 'index=main'), not commands like 'stats' or 'eval'. **Reality:** Macros can contain any valid SPL, including commands, functions, and even entire pipeline stages (like '| stats count by host'). They are not limited to base search filters. (The word 'macro' might seem to mean just a simple text replacement for a filter, but Splunk macros are full search snippets. This misconception can cause beginners to miss powerful use cases.)
- **Misconception:** A macro without arguments and a macro with arguments cannot have the same name, even if you define them separately. **Reality:** A single macro either has arguments or it does not. You cannot have two separate macros with the same name. The definition dictates whether it expects arguments, and calling it incorrectly causes an error. (Some programming languages allow overloading (same name, different parameters), so beginners might assume Splunk macros also support overloading. They do not.)

## Key takeaways

- A search macro is a reusable snippet of SPL, stored in Splunk's knowledge object system, that you insert into searches using the syntax \`$macroname$\$ or \`$macroname("argument")$\$.
- Macros solve the problems of repeating the same complex search logic, reducing typing errors, enforcing consistency, and simplifying updates across multiple searches.
- A macro expands at parse time, meaning the full search text is substituted before any events are processed, so a macro error causes a parse-time failure.
- Macros are scoped to the app in which they are created, and they can be shared with other users only if permissions are set appropriately.
- When a macro is defined with arguments, you must pass the correct number of quoted arguments when calling it; otherwise, the search will fail at parse time.
- Macros can contain any valid SPL, including base search terms, commands like stats, eval expressions, and even other macros, but they cannot be placed inside an eval string or a positional context where the expanded text would be syntactically invalid.

## FAQ

**What is the difference between a search macro and a saved search?**

A saved search is a complete search that can run on a schedule and trigger actions. A macro is just a reusable search snippet that you insert into other searches. You cannot run a macro by itself; it must be part of a larger search.

**Can I use a macro inside an eval command?**

No. The eval command expects expressions inside double quotes or backticks for field values, but macro syntax uses backticks with dollar signs, which is different. You cannot use a macro directly inside an eval function like 'eval x=$mymacro$()'.

**What happens if I delete a macro that another search uses?**

Any search that references a deleted macro will fail at parse time with an error like 'Error in search: Unknown search macro'. You must recreate the macro or update the searches to remove the reference.

**Can I use a macro created in one app in another app?**

Not by default. Macros are scoped to the app in which they are created. To use it in another app, you must either set the macro's permissions to 'Global' (if allowed) or duplicate the macro in the other app.

**How do I pass more than one argument to a macro?**

In the macro definition, use placeholders like $arg1$ and $arg2$. Then call it with comma-separated quoted values: `$macroname("value1", "value2")$`. The order of arguments in the call matches the order of placeholders in the definition.

**What are backticks in macro syntax and why do I need them?**

Backticks are required around the macro name when calling it: `$macroname$`. This tells Splunk that the text inside the backticks is a macro reference to be expanded, not a literal string. Without backticks, Splunk interprets the text as a normal search term.

## Check your understanding

1. **What is the correct syntax to call a macro named 'all_errors' that takes no arguments?**

   Answer: \`$all_errors$\$ (with two dollar signs, backticks, and no parentheses).

2. **A macro named 'user_search' is defined with one argument. What happens if you call it as \`$user_search$\$ without any argument?**

   Answer: The search will fail at parse time because the macro expects an argument and none was provided, leaving a placeholder unresolved.

3. **Where in the Splunk UI do you create a new search macro?**

   Answer: Settings > Knowledge > Search macros, then click 'New'.

4. **Can a search macro call another search macro?**

   Answer: Yes, you can nest macros, as long as there are no circular references. Macro A can contain `$macroB$` in its definition.

5. **If a macro's definition contains 'index=web status=404', and you later change the definition to 'index=web status=500', do you need to update every search that uses the macro?**

   Answer: No. Changing the macro definition automatically updates every search that references it, because the macro is expanded at parse time using the latest definition.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/splunk-core-certified-power-user/macros-creation-and-usage
