Create Playbook with a few tasks and another playbook

243 views Asked by At

Currently I'm searching for a solution, where I can create a Variable and then import the Playbook with the variable.

Here is my code:

- name: test
  hosts: localhost
  vars:
    ansible_python_interpreter: /usr/bin/python3
    playbook1: server_provision
    playbook2: server_provision_oracle
  gather_facts: no
  tasks:
  - name: define Variable with when condition
    set_fact:
      server_provision: "{{ playbook1 }}"
    when: OS == "RHEL"

  - name: store variable to file
    copy:
      content: "server_provision: {{ server_provision }}"
      dest: /tmp/server_provision.yml
    when: OS == "RHEL"

  - name: define Variable with when condition
    set_fact:
      server_provision: "{{ playbook2 }}"
    when: OS == "Oracle"

  - name: store variable to file
    copy:
      content: "server_provision: {{ server_provision }}"
      dest: /tmp/server_provision.yml
    when: OS == "Oracle"


- name: test
  vars_files:
    - /tmp/server_provision.yml
  import_playbook: "{{ server_provision }}.yaml"

But when I execute the playbook, i'm getting the error, that the variable server_provision has no value.

The Problem is that my unimportet playbook doesn't get executet, it starts with the importet one.

Do you have a solution for this?

1

There are 1 answers

6
Spirit On

You can use pre_tasks. Pre Taks are executed before the tasks section. Ansible Docs

Something like this:

---
  hosts: localhost
  vars:
    ansible_python_interpreter: /usr/bin/python3
    playbook1: server_provision
    playbook2: server_provision_oracle
  gather_facts: no

  vars_files:
    - /tmp/server_provision.yml

  pre_tasks:
  - name: define Variable with when condition
    set_fact:
      server_provision: "{{ playbook1 }}"
    when: OS == "RHEL"

  - name: store variable to file
    copy:
      content: "server_provision: {{ server_provision }}"
      dest: /tmp/server_provision.yml
    when: OS == "RHEL"

  - name: define Variable with when condition
    set_fact:
      server_provision: "{{ playbook2 }}"
    when: OS == "Oracle"

  - name: store variable to file
    copy:
      content: "server_provision: {{ server_provision }}"
      dest: /tmp/server_provision.yml
    when: OS == "Oracle"

  tasks:
    - name: test
      import_playbook: "{{ server_provision }}.yaml"