github-apigithub-cli

gh api pass array field


I am trying to use gh api --method PUT orgs/<ORG>/actions/permissions/selected-actions that accepts 3 fields: one of them patterns_allowed. I have tried multiple ways to pass the data, but I always get

{
  "message": "Invalid request.\n\nFor 'properties/patterns_allowed', \"...\" is not an array.",
  "documentation_url": "https://docs.github.com/rest/reference/actions#set-allowed-actions-for-an-organization"
}

One of this attempts looks like this:

ALLOWED="foo,bar"
gh api --method PUT \
    orgs/${{github.repository_owner}}/actions/permissions/selected-actions \
    --field "github_owned_allowed=true" \
    --field "verified_allowed=false" \
    --field "patterns_allowed=[$ALLOWED]"

What is the proper way to pass array type field?


Solution

  • gh api --field doesn't accept JSON arrays, it's an open issue for the project as cli/cli issue #1484.

    What you'd have to do instead is provide the JSON payload by specifying it directly as --input, so you have to create the JSON separate from the command, like in the following where I'm creating it as a heredoc string and then piping it into the gh api command:


    #!/bin/bash
    
    # This needs to be quoted correctly for substituting
    # as the elements of a JSON list
    ALLOWED='"foo","bar"'
    
    # Using a heredoc to make our JSON payload
    read -r -d '' PAYLOAD <<-JSON
    {
        "github_owned_allowed": true,
        "verified_allowed": false,
        "patterns_allowed": [${ALLOWED}]
    }
    JSON
    
    echo "$PAYLOAD" | gh api --method PUT \
        orgs/YOUR_ORG/actions/permissions/selected-actions \
        --input -
    

    This could be made slightly less clunky if you have jq, but I assumed no extra tools on your part.