I'm trying to get going with some more advanced Ansible playbooks and have hit a wall. I'm trying to get Ansible to do what this /bin/bash 'for' loop does;
for i in $(</filename.txt);do '/some/command options=1 user=usera server=$i';done
filesnames.txt contains 50-100 hostnames.
I can't use jinja templates as the command has to be run, not just the config file updated.
Any help would be greatly appreciated.
Thanks in advance,
Jeremy
you can use jinja templates, but differently
your specific code is not doing something that is most advisable
for multi-line code you should use shell module.
example of multi-code piece of call:
- name: run multiline stuff
shell: |
for x in "${envvar}"; do
echo "${x}"
done
args:
executable: /bin/bash
note I'm explicitly setting executable, which will ensure bash-isms would work.
I just used envvar as an example, of arbitrary environment variable available.
if you need to pass specific env variables, you should use environment clause of the call to shell module, refer to: http://docs.ansible.com/ansible/playbooks_environment.html
For simple variables you can just use their value in shell: echo "myvar: {{myvar}}"
If you wish to use an ansible list/tuple variable inside bash code, you can make it bash variable first. e.g. if you have a list of stuff in mylist, you can expand it and assign into a bash array, and then iterate over it. the shell code of the call to shell would be:
mylist_for_bash=({{mylist|join(" ")}})
for myitem in "${mylist_for_bash[#]}"; do
echo "my current item: ${myitem}"
done
Another approach would be to pass it as string env variable, and convert it into an array later in the code.
NOTE:
of course all this works correctly only with SPACELESS values
I've never had to pass array with space containing items
Related
The real case:
Every time I set up my environment, I'd like to check and – create if are not existing – certain environment variables. So, instead of doing it manually all the time, I thought it would be great if I can have a file which stores the environment name env_N and environment value env_V pairs. Amongst all text file formats, the yaml looks the simplest and the more natural to store that info.
So what I thought it would be great if I suck in the yaml file with my environmental variables using yq and create associative array ready to be iterated over by zsh foreach loop:
foreach entry in my_assoc_arr
do
check_and_create(entry.env_N, entry.env_V)
done
with the final result of:
$ echo $env_N1
env_V1
$ echo $env_N2
env_V2
$ echo $env_N3
env_V3
...
The problem I'm having is to get my yaml to associative array using yq in shell zsh script.
After applying each suggestion from the comments, I was unable to create my associative array from yaml with yq. I had errors from yq like bad syntax or script worked or not depends on whether I have #!/bin/zsh switched on or commented out.
I got impression that my task is simple, but somehow I cant achieve this.
What I'm doing wrong here?
PS: I'm using zsh on macOS
Why would you want to use Yaml for this, when it’s much easier to write a simple shell script for it?
Simply create a text file with the following line for each env var:
# Set $FOO to 'bar' if $FOO does not yet exist.
export ${FOO=bar}
Then source this file from your shell (or another script).
See https://zsh.sourceforge.io/Doc/Release/Expansion.html#Parameter-Expansion
For the life of me, I can't figure out how to declare and use new variables inside a shell block in a groovy script.
For example, this shell block -
sh """
export earlist='abc.ear,def.ear'
echo $earlist;
"""
throws an error saying
No such property: earlist for class: GroovyUserScript
If I add a def earlist before the sh, then it throws error saying -
No signature of method: GroovyUserScript.sh() is applicable for
argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [
export earlist='abc.ear,def.ear' echo ;
Can someone please help me with how to declare and then use variable inside a shell block, in a groovy script?
After consulting with senior experts at my workplace, I found the solution I was looking for.
The problem with this code -
sh """
export earlist='abc.ear,def.ear'
echo $earlist;
"""
is that when I say $earlist, the compiler looks for a groovy variable named earlist and doesn't find it. Since earlist there is a shell variable, I need to escape the $. So, the correct code is -
sh """
earlist='abc.ear,def.ear'
echo \$earlist;
"""
Bonus TIL - if I access a groovy variable inside a shell block, the access is Read-Only. I can't edit the value of the groovy variable, even temporarily within the shell block. If I do want to do that, I can assign the groovy variable to a shell variable, manipulate the shell variable value, save the modified value in a file and when the shell block ends, read the file into the original groovy variable.
Use a triple single quoted string instead, which doesn't interpolate variables:
sh '''
export earlist='abc.ear,def.ear'
echo $earlist;
'''
See here the documentation on triple single quoted strings: http://groovy-lang.org/syntax.html#_triple_single_quoted_string
Here a overview of the available string types in Groovy: http://groovy-lang.org/syntax.html#_string_summary_table
I've read that while using a cron you define variables like always:
var = <value>
But you can't use variable values on < value > such as:
PATH=$PATH
So how could I introduce the PATH inside PATH plus HOME/FOLDER for instance? Normally I would do...
PATH=$HOME/FOLDER:$PATH
But if what I've read is correct, that isn't available...right?
my crontab(5) page agrees with you:
The value string is not parsed for environmental substitutions or replacement of variables, thus lines like
PATH = $HOME/bin:$PATH
will not work as you might expect.
However, if you're specifically interested in $HOME, you can use this:
An alternative for setting up the commands path is using the fact that many shells will treat the tilde(~) as substitution of $HOME, so if you use bash for your tasks you can use this:
SHELL=/bin/bash
PATH=~/bin:/usr/bin/:/bin
I would like to know if I can substitute a variable twice.
For example:
#global variable
TEST_SERV_EXT=""
#variables become from myconf.sh
TEST_SERV_EXT_FO='foo01'
TEST_SERV_EXT_BR='bar01'
I want dynamically construct those last two and assign them in TEST_SERV_EXT.
I tried something like this ${$TEST_SERV_COMP} but I'm getting "bad substitution" message.
I need something like php's feature "$$" or tcl's subst command.
Regards,
thandem
TEST_SERV_COMP=TEST_SERV_EXT_FO
TEST_SERV_EXT=${!TEST_SERV_COMP}
Look for indirect expansion in the bash manual.
I have some code that creates a variable of some name automatically and assigns some value to it. The code is something like the following:
myVariableName="zappo"
eval "${myVariableName}=zappo_value"
How would I access the value of this variable using the automatically generated name of the variable? So, I'm looking for some code a bit like the following (but working):
eval "echo ${${myVariableName}}"
(... which may be used in something such as myVariableValue="$(eval "echo ${${myVariableName}}")"...).
Thanks muchly for any assistance
If you think this approach is madness and want offer more general advice, the general idea I'm working on is having variables defined in functions in a library with such names as ${usage} and ${prerequisiteFunctions}. These variables that are defined within functions would be accessed by an interrogation function that can, for instance, ensure that prerequisites etc. are installed. So a loop within this interrogation function is something like this:
for currentFunction in ${functionList}; do
echo "function: ${currentFunction}"
${currentFunction} -interrogate # (This puts the function variables into memory.)
currentInterrogationVariables="${interrogationVariables}" # The variable interrogationVariables contains a list of all function variables available for interrogation.
for currentInterrogationVariable in ${currentInterrogationVariables}; do
echo "content of ${currentInterrogationVariable}:"
eval "echo ${${currentInterrogationVariable}}"
done
done
Thanks again for any ideas!
IIRC, indirection in bash is by !, so try ${!myVariableName}
Try:
echo ${!myVariableName}
It will echo the variable who's name is contained in $myVariableName
For example:
#!/bin/bash
VAR1="ONE"
VAR2="TWO"
VARx="VAR1"
echo ${VARx} # prints "VAR1"
echo ${!VARx} # prints "ONE"