0
votes

I'm trying to send a json variable ( {{parameter_var}} ) to a Jenkins job from Ansible using a curl call. Here is the task I'm using:

- name: Call Jenkins Job
  shell: curl -H "crumb:{{ response.json.crumb }}" '{{ jenkinshost }}/job/{{ jenkinsjob }}/buildWithParameters?token={{ jenkinstoken }}' --data-urlencode json='{"parameter": [{"name":"parameter", "value":\""{{ parameter_var }}"\"}]}'

The error I'm getting is:

             Syntax Error while loading YAML.\n  mapping values are not allowed in this context

Ansible says the issue is:

           YAML thought it was looking for the start of a\nhash/dictionary and was confused to see a second "{".

It seems that instead of accepting {{ parameter_var }} as a variable, it's trying to read it as just a value of "{{ parameter_var }}". I tried a few ways of adding or escaping quotes, but can't seem to figure out what Ansible/YAML is looking for. Am I just adding my quotes wrong, or can I just not send a variable using this method?

I printed out my {{ parameter_var }}. There's nothing unusual about it, so I don't think that's the issue:

{
    "msg": {
        "msg": "All items completed",
        "changed": false,
        "results": [
            {
                "content_length": "142", 
                 ...
            } ...
}

The goal I'm trying to accomplish is to set parameter "parameter" in Jenkins to the value of {{ parameter_var }}

Here's where I found the syntax for sending the json to Jenkins: https://wiki.jenkins.io/display/JENKINS/Remote+access+API

1

1 Answers

2
votes

There are a lot of things that need addressing in your question:

  • you should not be shell-ing out to curl when there is a uri: module in ansible designed for that purpose
    • related to that, you left off --fail from your curl, so a non-200 response will cause the shell: to exit 0 which is almost certainly not what you intended
  • you cannot have a : character followed by whitespace in a yaml document because that's how yaml defines keys in a dict
  • you should not try and build up JSON using jinja2 templates, rather build up the structure in a dict or list and feed it through | to_json to ensure correct quoting

However, if you insist on that syntax specifically, you can fix it with some light editing:

- name: Call Jenkins Job
  shell: >-
     curl --fail -H "crumb:{{ response.json.crumb }}" 
     '{{ jenkinshost }}/job/{{ jenkinsjob }}/buildWithParameters?token={{ jenkinstoken }}'
     --data-urlencode json={{ json_data | to_json | quote }}
  vars:
    json_data:
      parameter:
      - name: "parameter"
        value: '{{ parameter_var }}'