Reputation: 1782
I have playbook running fine when I have environment variables and tasks defined in one single playbook without roles.
But when I structure my project into roles, I see that running tasks is not finding the environment variables that are set from the original playbook.
Any hint how to set env variables so they are available for all roles inside a playbook?
Do I need to specify the environment variables in tasks/main.yaml
file?, if yes how should do this exactly?
cat playbook.yaml
-
name: Deploy Team Services Playbook
hosts: all
environment:
PATH: "{{ ansible_env.PATH }}:/usr/local/bin"
KUBECONFIG: "{{ ansible_env.HOME }}/.kube/config/{{ ansible_env.USER }}.kubeconfig"
roles:
- prereq1_setup
- prereq2_k8s
prereq1_setup\tasks\main.yaml
- name: "Validate kubeconfig set?"
shell: echo {{ ansible_env.KUBECONFIG }}
failed_when: "'KUBECONFIG' not in ansible_env"
Above works if I don't use roles and directly add tasks below. currently, am getting error as
output:
|TASK [prereq1_setup : Validate kubeconfig set?] *****************************************************
fatal: [target1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'KUBECONFIG'\n\nThe error appears to be in '/Users/testu/ansible/ansible-team/team_deploy/roles/prereq1_setup/tasks/main.yaml': line 57, column 9, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: \"Validate kubeconfig set?\"\n ^ here\n"}
Upvotes: 1
Views: 4255
Reputation: 33158
Any hint how to set env variables so they are available for all roles inside a playbook?
The mechanism you are using is correct, and that environment variable is being correctly set, but it is set in the environment, and not in the ansible facts. Those facts are gathered before the playbook boots up, and thus your environment:
happens after fact gathering, which explains why ansible_env
does not contain it
You have a few paths forward, depending on what you prefer:
gather_facts: no
and invoke setup:
manually)ansible_env
, with the trust that it is actually there, and just use the commands which need the environment variableenvironment:
and to the ansible tasksIf you want the first one, it would look like:
-
name: Deploy Team Services Playbook
hosts: all
gather_facts: no
environment:
whatever: goes here
pre_tasks:
- setup:
roles:
- and so forth
You can confirm the second via:
- name: ensure $KUBECONFIG is set
shell: echo $KUBECONFIG
And the third would look like:
- hosts: all
environment:
alpha: beta
vars:
alpha: beta
roles:
- # now {{ alpha }} is available to ansible and as $alpha in `commands:`
Upvotes: 1