'Pass parameter from .sh file to .yml file?
I am new to Ansible as well as Ubuntu system also. I want to pass the multiple variables from .sh file to .yml. I have plan to store all input variables in an array then passing the variable one by one using for loop while calling the file distributed-setup.yml.
Currently, I am trying to pass a variable.For that,I am following the below steps.
While executing the
First.shfile I am passing the a variables likeFirst.sh Input.yamlFirst.shfile is like thisecho $1 ansible-playbook distributed-setup.yml --extra-vars="v:$1" -${1:-v} | tee output.txtDistributed-setup.yml
--- - name: Executing slaves hosts: slave gather_facts: no vars: v: "{{lookup('env','v') }}" contents: "{{ lookup('file','/home/ubuntu/Ansible-setup/Distributed-Ubuntu-Setup/Input/Input.yaml') | from_yaml }}" log: "{{ contents['log'][0] }}" timeout: "{{ contents['ansible-timeout'][0] }}"
In the line, contents: I need to use variable 'v' instead of Input.yaml.
How to do this?
Solution 1:[1]
One of the easiest ways to do this is through the environment
someVar=value ansible-playbook ...
and then, inside your Ansible code, you can refer to ansible_env.someVar. You can also export the variable and not need to define it on the same line.
To make this a bit more concrete for your use case:
input_yaml=/home/ubuntu/Ansible-setup/Distributed-Ubuntu-Setup/Input/Input.yaml
export input_yaml
ansible-playbook distributed-setup.yml
...and in your Ansible file:
contents: "{{ lookup('file', ansible_env.input_yaml) | from_yaml }}"
Solution 2:[2]
This is how you could use your variable v within other ones:
---
- hosts: localhost
connection: local
gather_facts: no
vars:
v: "{{ lookup('env','v') }}"
b: "{{ lookup('file','/tmp/{{ v }}') | from_yaml }}"
tasks:
- name: set contents
set_fact:
contents: "{{ lookup('file','/tmp/{{ v }}') | from_yaml }}"
- name: debug
debug:
msg: "{{ b }} == {{ contents }}"
when: b == contents
v will get the value of the existing environment var v and then use it on var b later in a task just in case is created another variable named contents with the value of b in this case using set_fact
For testing do:
$ export v=foo
$ date > /tmp/foo
$ ansible-playbook test.yml
It will set v to foo then will create a file in /tmp/foo with the current date (output of the date command)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Charles Duffy |
| Solution 2 |
