For example, the relevant part of my playbook looks like this:
tasks:
- name: test
script: ../test.sh
...
And for my test.sh there is this one line of code that will execute a python script as such:
python run.py --inputvar hello
Is there a way to change the inputvar value within the .sh file from "hello" to something else from the playbook?
Edit: Appreciate @seshadri_c 's help on this. Guess this question shouldve been tagged under shell scripts.
CodePudding user response:
The simplest way to parse arguments in a shell script is using positional arguments - $1
, $2
, etc.
Given a test.sh
script with:
#!/bin/bash
python run.py --inputvar $1
And running it as:
/bin/bash test.sh arg1
will pass the value of $1
to run.py
as --inputvar arg1
.
Same thing can be run from Ansible task:
tasks:
- name: test
script: ../test.sh arg1
CodePudding user response:
There are more options.
- The first one might be lineinfile, e.g. the task below is idempotent
- lineinfile:
path: test.sh
regex: '^python run.py --inputvar (.*)$'
line: 'python run.py --inputvar {{ my_var|default("hello") }}'
gives
TASK [lineinfile] *******************************************************
ok: [localhost]
If you define the variable my_var (See Variable precedence: Where should I put a variable?)
my_var: hello world
The task will change the line in the file. (Running the playbook with options --check --diff)
TASK [lineinfile] ********************************************************
--- before: test.sh (content)
after: test.sh (content)
@@ -1,3 1,3 @@
#!/usr/bin/sh
-python run.py --inputvar hello
python run.py --inputvar hello world
changed: [localhost]
The next option might be template, e.g. the template test.sh.j2 and the task below give the same results
shell> cat test.sh.j2
#!/usr/bin/sh
python run.py --inputvar {{ my_var|default("hello") }}
- template:
src: test.sh.j2
dest: test.sh