user3292394
user3292394

Reputation: 649

Pass nested Ansible vars into playbook inventory file

I am wondering is it possible to pass in the --extra-vars when running an ansible-playbook in order to inject the variables into an inventory file, which I am using to run my playbook.

sample playbook

- name: "Create CI pipeline"
  hosts: all
  tasks:
  - name: "Create PreCodeReview jobs"
    tags:
      - jenkins
      - jenkins-jobs
    when: jenkins is defined
    local_action:
      module: jenkins_job
      url: "{{ jenkins.url }}"
      user: "{{ jenkins.username }}"
      token: "{{ jenkins.access_token }}"
      name: "{{ jenkins.component.name }}_PreCodeReview"
      config: "{{ lookup('template', '../templates/jenkins/add-pre-code-config.xml') }}"

  - name: "Create Release jobs"
    tags:
      - jenkins
      - jenkins-jobs
    when: jenkins is defined
    local_action:
      module: jenkins_job
      url: "{{ jenkins.url }}"
      user: "{{ jenkins.username }}"
      token: "{{ jenkins.access_token }}"
      name: "{{ jenkins.component.name }}_Release"
      config: "{{ lookup('template', '../templates/jenkins/add-release-config.xml') }}"

I am looking to pass in jenkins.component.name at run time, I have attempted this with the following jenkins.component.name=<name> and "{'jenkins':{'component':{'name':<name>}}}"

This didn't work.

Here is the inventory I am using to run the playbook

sample inventory

all:
  hosts:
    local:
      ansible_host: 127.0.0.1
      ansible_connection: local
      project_name: magic_proj
      jenkins:
        url: https://my/jenkins
        username: admin
        access_token: f96hjfg54354b3e8512d491fb471fd
        keep_builds: 20
        components:
          - name: <repo_name>
            repository: <repo_url>

Upvotes: 0

Views: 932

Answers (1)

mdaniel
mdaniel

Reputation: 33203

I am looking to pass in jenkins.component.name at run time, I have attempted this with the following jenkins.component.name=<name> and "{'jenkins':{'component':{'name':<name>}}}"

You were very close: the --extra-vars wants either key=value pairs, JSON, YAML, or @./some/file, as specified in the fine manual

Regrettably, what you provided was Python syntax, and not JSON syntax; if you change your command line to --extra-vars '{"jenkins":{"component":{"name":<name>}}}'

update: However, even that has a problem: it appears that for dict structures, ansible does not merge inventory dicts and extra-var dicts, so you will need to either choose a "flat" extra-var name (such as almost what you also attempted: --extra-vars '{"jenkins_component_name": ""}') or manually merge the structures together in your playbook (perhaps via pre_tasks: or similar)

Upvotes: 1

Related Questions