How to pass environment Variables to post body

Not sure how to pass it to the body of request
It is fine with csv feeder

.body(StringBody(
“”"
{“user”:"${user}",
“password”:"${password}"
“”")).asJson

but i’d like these variables to be environment Variables

Tried smth like
val login = sys.env(“PORTAL_ADMIN”)

and then
.body(StringBody(
“”"
{“user”:"${login}",
“password”:"${password}"
“”")).asJson

but no luck

Hi nikolay,

Be aware that Gatling can use two levels of string interpolation.
In documentation and different tutorials, we warn about not using the scala string interpolator (string prefixed with an s) because it is hard to mix with Gatling EL.

In your case, you want to transform the string with an environment variable.

Two available solutions come in mind:

  1. Give the variable to session

val login = sys.env(“PORTAL_ADMIN”)

val step =
exec(session => session.put(“myLogin”, login))
.exec(http(“my request”)
.body(StringBody("""{“user”:"${login}"}""")).asJson)
Note that it is close to your solution but with the session modification extra step.

  1. Use scala string interpolator

val login = sys.env(“PORTAL_ADMIN”)

val step =
exec(http(“my request”)

.body(StringBody(s"""{“user”:"${login}"}""")).asJson)

Note the “s” before the string in the StringBody.
Be aware that the whole string will be interpolated by scala first.

If you need to mix both session variables (or other EL syntax) AND global variables, you may use it with escaping the scala string interpolator.

Exemple:

val login = sys.env(“PORTAL_ADMIN”)

val step =
exec(http(“my request”)

.body(StringBody(s"""{“user”:"${login}", “password”: “$${fromSessionPassword}”}""")).asJson)

Note:

  • the s before to be a scala interpolable string
  • the double $$ before the session variable (scala will interpolate the $$ to $)

If you need (complicated one :stuck_out_tongue: ) to give a “$” in the final body, you will have to quadruple it

s"$$$$" (scala interpretable string) → “$$” (gatling EL) → “$” (final body)

Sébastien,
Many thanks for the prompt reply!

Did it work as intended?

Erratum, in the first solution, we should use the newly myLogin session variable

val login = sys.env(“PORTAL_ADMIN”)

val step =
exec(session => session.put(“myLogin”, login))
.exec(http(“my request”)
.body(StringBody("""{“user”:"${myLogin}"}""")).asJson)

Yes, it does.
I’m using now your first solution .
Just changed put to set and use new session variable.
Thanks again)
exec(session => session.set(“myLogin”, login))