# How to refer the value of variable in code block inside add\_field?

**URL:** https://discuss.elastic.co/t/how-to-refer-the-value-of-variable-in-code-block-inside-add-field/1815
**Category:** Logstash
**Created:** [June 3, 2015, 10:17am UTC](https://discuss.elastic.co/t/how-to-refer-the-value-of-variable-in-code-block-inside-add-field/1815 "2015-06-03T10:17:08Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![Saket\_Kumar](https://avatars.discourse-cdn.com/v4/letter/s/c57346/32.png) [@Saket\_Kumar](https://discuss.elastic.co/u/Saket_Kumar)
#### Post date: [June 3, 2015, 10:17am UTC](https://discuss.elastic.co/t/how-to-refer-the-value-of-variable-in-code-block-inside-add-field/1815/1 "2015-06-03T10:17:08Z")

</div>

ruby {  
code =\> "

```
		filename = File.basename(event['path'], '.*')
		value = filename.split('_')
		x = value[0]
		y = value[1]+'_' + value[2] +'_'+ value[3]
		z = value[4]
	
	  "
	
add_field => { 
		"Test_Id" => "%{x}"
		"Run_Id" => "%{y}"
		"URL" => "%{z}"
	     }		

```

I tried above but no luck. Test\_Id gets assigned to %{x} instead value of 'x'. same observed for Run\_Id & URL.

---

<div class="post-metadata">

### Author: ![magnusbaeck](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/magnusbaeck/32/44943_2.png) [@magnusbaeck](https://discuss.elastic.co/u/magnusbaeck)
#### Post date: [June 3, 2015, 10:32am UTC](https://discuss.elastic.co/t/how-to-refer-the-value-of-variable-in-code-block-inside-add-field/1815/2 "2015-06-03T10:32:10Z")

</div>

In your example, `x`, `y`, and `z` are local variables in the Ruby code snippet. They won't be visible to the outside unless you assign the values to Logstash fields, for example like this:

```
event['x'] = value[0]
event['y'] = value[1] + '_' + value[2] + '_' + value[3]
event['z'] = value[4]

```

But again, you're overcomplicating things. As I said yesterday this is a perfect job for grok. Something like this should work (depending on exactly what the input looks like and exactly what you expect to get from it):

```
filter {
  grok {
    match => [
      "path",
      ".*/(?<Test_Id>[^/_]+)_(?<Run_Id>[^/]+)_%(?<URL>[^/]+)
    ]
  }
}
```

---

<div class="post-metadata">

### Author: ![Saket\_Kumar](https://avatars.discourse-cdn.com/v4/letter/s/c57346/32.png) [@Saket\_Kumar](https://discuss.elastic.co/u/Saket_Kumar)
#### Post date: [June 4, 2015, 6:55am UTC](https://discuss.elastic.co/t/how-to-refer-the-value-of-variable-in-code-block-inside-add-field/1815/3 "2015-06-04T06:55:13Z")

</div>

Thanks magnus!

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [July 6, 2017, 5:38am UTC](https://discuss.elastic.co/t/how-to-refer-the-value-of-variable-in-code-block-inside-add-field/1815/4 "2017-07-06T05:38:37Z")

</div>


