4

I have a trivial task that I am stuck to write salt state for. I need to call REST endpoint using curl with json body. This is

curl localhost/endpoint -d '{"some" : "data"}'

My idea was to simply take this and put it into salt state by using cmd.run. Does not work. So far I have this:

{%- set data = {'some': 'data'} %}

Use echo instead of curl:
  cmd.run:
    - name:  echo '{{ data|json }}'

And this gives me

failed: Unknown yaml render error; line 5

Use echo instead of curl:
  cmd.run:
    - name:  echo '{"some": "data"}'    <======================

I have Salt version 2014.7.1

Martin
  • 708
  • 2
  • 10
  • 20

2 Answers2

10

For me the problem was the ":" within the curl command that was interpreted as YAML (see: How to escape indicator characters (i.e. : or - ) in YAML)

I ended up using the multi-line approach. That allows me to write the command with no escaping while variables (e.g pillar data) are still interpreted correctly.

E.g.

Salt state description:
  cmd.run:
    - name: >-
        curl -X GET  "https://api.example.com/client/{{ pillar['client_id'] }}" -H  "X-Auth-Email: name@example.co.za" -H "X-Auth-Key: {{ pillar['api_key'] }}" -H "Content-Type: application/json" --data '{"some_json":true}'
Heinrich Filter
  • 5,760
  • 1
  • 33
  • 34
0

When working with json it is sometimes easier to avoid the jinja renderer altogether. The following example uses the pybojects renderer (which is nice for a lot of other reasons too).

echo.sls:

#!pyobjects
import json

data = {'some': 'data'}

def dump(d):
   return "'" + json.dumps(d).replace("'", "'\\''") + "'"

Cmd.run("echo {}".format(dump(data)))

Note that the custom dump function definition and usage is added for the sake of completeness.

mgwilliams
  • 78
  • 1
  • 2