Curl возвращает недопустимую ошибку JSON в сценарии Jenkins Pipeline, но возвращает ожидаемый ответ при запуске оболочки bash или в задании Jenkins Freestyle - PullRequest
0 голосов
/ 19 мая 2019

Я пишу задание Jenkins Pipeline для настройки инфраструктуры AWS с помощью вызовов API в нашей собственной библиотеке-оболочке AWS CLI. Выполнение сырых сценариев bash на компьютере CentOS или в качестве задания Jenkins Freestyle проходит нормально. Тем не менее, он терпит неудачу в контексте конвейерной работы. Я думаю, что кавычки, возможно, должны отличаться для работы конвейера, но я не уверен, как.

После дальнейшего изучения я обнаружил, что команда curl возвращает неправильный ответ службы при запуске сценариев в задании конвейера Jenkins.

pipeline {
    agent any

    stages {
        stage('Checkout code from Git'){
            steps {
                 echo "Checkout code from a GitHub repository"
                // Checkout code from a GitHub repository
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: false, recursiveSubmodules: true, reference: '', trackingSubmodules: false]], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'xxxx', url: 'git@github.com:bbc/repo.git']]])
            }
        }
        stage('Call our internal AWS CLI Wrapper System API to perform an ACTION on a specified ENVIRONMENT') {
            steps {

                script {
                    if("${params.ENVIRONMENT}" == 'int' && "${params.ACTION}" == 'create'){
                        echo "ENVIRONMENT=${params.ENVIRONMENT}, ACTION=${params.ACTION}"
                        echo ""
                        sh '''#!/bin/bash
                            # Create Neptune Cluster for the Int environment
                            cd blah-db
                            echo "Current working directory is $PWD"
                            CLOUD_FORMATION_FILE=$PWD/infrastructure/templates/neptune-cluster.json
                            echo "The CloudFormation file to operate on is $CLOUD_FORMATION_FILE"
                            echo "Running jq to transform the source CloudFormation file"
                            template=$(jq -M '.Parameters.Env.Default="int"' $CLOUD_FORMATION_FILE)
                            echo "Echoing the transformed CloudFormation file: \n$template"
                            echo "Running curl to make the http request to our internal AWS CLI Wrapper System"
                            curl -d "{\"aws_account\":  \"1111111111\", \"region\": \"us-east-1\", \"name_suffix\":  \"cluster\", \"template\": $template}" \
                            -H 'Content-Type: application/json'  -H 'Accept: application/json' https://base.api.url/v1/services/blah-neptune/int/stacks \
                            --cert /path/to/client/certificate/client.crt --key /path/to/client/private-key/client.key
                            cd ..
                            pwd

                            # Set a timer to run for 300 seconds or 5 minutes to create a delay to allow for the Neptune Cluster to be fully provisioned first before adding instances to it.


                        '''

                    }
                }
            }
        }
    }
}

Фактический результат, который я получаю от вызова API:

{"error": "Invalid JSON. Expecting property name: line 1 column 1 (char 1)"}

1 Ответ

0 голосов
/ 20 мая 2019

попробуйте изменить локон следующим образом:

curl -d '{"aws_account":  "1111111111", "region": "us-east-1", "name_suffix":  "cluster", "template": $template}'

Или назначьте весь cmd переменной и распечатайте его, чтобы увидеть, как он вам нужен или нет.

cmd = '''#!/bin/bash
         cd blah-db
      ...
      '''

echo cmd // compare the output string to the cmd of freestyle job.

sh cmd
...