In an Azure DevOps pipeline template I need to pass variables as a dictionary to another template which will use an ansible task to process all keys in the dictionary.
The type: object
seems appropriate, but I’m looking for a working example.
main-template.yml
trigger:
- main
stages:
- stage: Deploy
jobs:
- job: DeployJob
pool:
vmImage: 'ubuntu-latest'
steps:
- template: ansible-template.yml
parameters:
ansibleVars:
var1: value1
var2: value2
ansible-template.yml
parameters:
- name: ansibleVars
type: object
default: {}
jobs:
- job: AnsibleJob
pool:
vmImage: 'ubuntu-latest'
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '3.x'
addToPath: true
- script: |
python -m pip install ansible-core
displayName: 'Install Ansible'
- script: |
echo "${{ parameters.ansibleVars }}" > vars.yml
displayName: 'Create vars file'
- task: Ansible@0
displayName: 'Run playbook'
inputs:
ansibleInterface: 'agentMachine'
playbookPathOnAgentMachine: './ansible/playbook.yml'
inventoriesAgentMachine: 'file'
inventoryFileOnAgentMachine: './ansible/inventory/hosts'
args: -vv -e @vars.yaml
failOnStdErr: false
2
Answers
According to the documentation, you can use vars from a JSON or YAML file:
In your pipeline you can use convertToJson to convert a parameter to a json string and then generate a json file and use it in your
Ansible@0
task.Example
Please note I’m assigning the json string to a task environment variable instead of using it directly in the script body – this way I don’t need to bother escaping quotes and other special characters:
You can reference the sample below to pass dictionary into the template YAML:
If you want to pass all the key-value pairs to the
args
field of the Ansible@0 task, you can set the template like as below.