In Ansible, how can I get default values of unrequired properties in a json schema when these unrequired properties are not defined in a config?

Viewed 132

I have the following json schema:

{
  ...

  "properties": {
    "gitlabUrl": {
      "description": "URL of the GitLab instance to use",
      "type": "string",
      "default": "https://gitlab.com"
    },
    "gitlabApiVersion": {
      "description": "Version of the GitLab API to use",
      "type": "string",
      "enum": [ "v3", "v4" ],
      "default": "v4"
    },
    "gitlabAccessToken": {
      "description": "Personal access token for accessing the GitLab API",
      "type": "string"
    }
  },

  "required": [
    "gitlabAccessToken"
  ]

}

Only gitlabAccessToken is a mandory property. Consider a config of the above schema which contains only the gitlabAccessToken property:

{
  "gitlabAccessToken": "XXXXXXXXXXXXXXXX"
}

If I pass the above config to my Ansible role which has the following task file:

---
- name: check variables
  debug:
    msg:
      - "gitlabUrl: {{ gitlabUrl }}"
      - "gitlabApiVersion: {{ gitlabApiVersion }}"
      - "gitlabAccessToken: {{ gitlabccessToken }}"

Ansible will complain that gitlabUrl and gitlabApiVersion are undefined. I don't want to make gitlabUrl and gitlabApiVersion mandatory in the json schema, but I still want these two variables to be automatically defined in Ansible with the default values specified in the json schema. How can I achieve this?

1 Answers

Create a dictionary of the default values, e.g.

    - set_fact:
        pd: "{{ properties|
                dict2items|
                json_query('[].{key: key, value: value.default}')|
                items2dict }}"

gives

  pd:
    gitlabAccessToken: null
    gitlabApiVersion: v4
    gitlabUrl: https://gitlab.com

Then use the dictionary to set the default values, e.g.

    - debug:
        msg:
          - "gitlabUrl: {{ gitlabUrl|default(pd.gitlabUrl) }}"
          - "gitlabApiVersion: {{ gitlabApiVersion|default(pd.gitlabApiVersion) }}"
          - "gitlabAccessToken: {{ gitlabAccessToken|default(pd.gitlabAccessToken) }}"
      vars:
        gitlabAccessToken: "XXXXXXXXXXXXXXXX"

gives

  msg:
  - 'gitlabUrl: https://gitlab.com'
  - 'gitlabApiVersion: v4'
  - 'gitlabAccessToken: XXXXXXXXXXXXXXXX'
Related