How to pass value to ansible command module - ansible

I am new to ansible and trying to write some basic playbook. I need to run a command via command module, but that command needs use a value derived from other command this is what I have:
+++++++++++++++++++++++++++++++++++++++++++
---
- name: Post SentinelOne Agent
hosts: all
tasks:
- name: user sentinel exist
command: /usr/bin/grep sentinelone /etc/passwd
register: user_exist
ignore_errors: yes
- name: Create sentinelone user using existing id, only if the user does not exist
command: "useradd -d /opt/sentinelone/home/ -u `ls -ld /opt/sentinelone/ | awk '{print $3}'`** -f 1 -l -g sentinelone -s /sbin/nologin sentinelone"
when: user_exist.rc == 1
- name: Check again to confirm user exist for copy purpose
command: /usr/bin/grep sentinelone /etc/passwd
register: does_user_exist
ignore_errors: yes
- name: Whitelist sentinelone user ... Copy line from /etc/passwd
command: echo "`cat /etc/passwd | grep -i sentinelone`" >> /etc/crypt/passwd_local
when: does_user_exist.rc == 0
- name: Whitelist sentinelone user ... Copy line from /etc/shadow
command: echo "`cat /etc/shadow | grep -i sentinelone`" >> /etc/crypt/shadow_local
when: does_user_exist.rc == 0
+++++++++++++++++++++++++++++
get error:
for
command: "useradd -d /opt/sentinelone/home/ -u `ls -ld /opt/sentinelone/ | awk '{print $3}'`** -f 1 -l -g sentinelone -s /sbin/nologin sentinelone"
STDERR:
useradd: invalid user ID '`ls'
MSG:
non-zero return code

Related

Unterminated quoted string error while running 'kubectl exec' using shell

I am trying to run a kubectl exec command to run the command in the respective containers and transfer their outputs to a file using a shell script. I have the data in a YAML file with name of container, pod name, command and the file name where it is to be stored. I have parsed the YAML file using yq package and am trying to execute the commands. The commands having no quotes are executed successfully but the ones containing quotes result in an error. Collect execs contain name of the file and command.
I have tried running the commands normally on the command line and they seem to execute without any error. The error comes when I store them in a variable and then execute them.
Also doesn't work if I use " or ' or change ' to ".
FUNCTION
get_execs() {
mkdir ${EXECDIR}
for con in $(yq '.containers[] | .name' ${YFILE})
do
# echo $con
x=$(i=$con yq '.containers[] | select(.name == env(i)) | .collect_execs[] | .name' ${YFILE})
# printf "%s\n" "$x"
mkdir ${EXECDIR}/$con
for j in $x
do
c=$(i=$con p=$j yq '.containers[] | select(.name == env(i)) | .collect_execs[] | select(.name == env(p)) | .cmd' ${YFILE})
pod=$(i=$con yq '.containers[] | select(.name == env(i)) | .pod' ${YFILE})
# printf "%s abc\n" "$c"
kubectl exec -n ${NAMESPACE} $pod -c $con -- $c > ${EXECDIR}/$con/$j
done
done
}
YAML FILE STRUCTURE:
containers:
- name: otg-port-eth1-protocol-engine
pod: otg-port-eth1
collect_execs:
- name: resource-usage
cmd: top -c -n 2 -b -H -w 120
- name : disk-space
cmd : df -H
- name: cpu-info
cmd: cat /proc/cpuinfo
- name: interface-manager-threads-iter1
cmd : sh -c 'gdb --eval-command "set pagination 0" --eval-command "thread apply all bt" --batch --pid $(pidof InterfaceManager)'
- name: interface-manager-threads-iter2
cmd : sh -c 'gdb --eval-command "set pagination 0" --eval-command "thread apply all bt" --batch --pid $(pidof InterfaceManager)'
- name: interface-manager-shared-sos
cmd: sh -c 'cat /proc/$(pidof InterfaceManager)/maps'
- name: netstat
cmd: netstat -an
- name: dmesg
cmd : dmesg
- name : ifconfig
cmd : ifconfig
ERROR
--eval-command: 1: Syntax error: Unterminated quoted string
command terminated with exit code 2
--eval-command: 1: Syntax error: Unterminated quoted string
command terminated with exit code 2
/proc/$(pidof: 1: Syntax error: Unterminated quoted string
command terminated with exit code 2
--eval-command: 1: Syntax error: Unterminated quoted string
command terminated with exit code 2
--eval-command: 1: Syntax error: Unterminated quoted string
command terminated with exit code 2
/proc/$(pidof: 1: Syntax error: Unterminated quoted string
command terminated with exit code 2
The commands running with sh -c are causing the errors. To fix this, I changed the YAML structure and broke up the commands into 2 parts: precmd and cmd.
- name: resource-usage
cmd: top -c -n 2 -b -H -w 120
- name : disk-space
cmd : df -H
- name: cpu-info
cmd: cat /proc/cpuinfo
- name: interface-manager-threads-iter1
precmd : sh -c
cmd : 'gdb --eval-command "set pagination 0" --eval-command "thread apply all bt" --batch --pid $(pidof InterfaceManager)'
- name: interface-manager-threads-iter2
precmd : sh -c
cmd : 'gdb --eval-command "set pagination 0" --eval-command "thread apply all bt" --batch --pid $(pidof InterfaceManager)'
- name: interface-manager-shared-sos
precmd : sh -c
cmd: 'cat /proc/$(pidof InterfaceManager)/maps'
And then run the check:
if [ ! "$pc" = null ]
then
kubectl exec -n ${NAMESPACE} $pod -c $con -- $pc "$c" > ${EXECDIR}/$con/$j
else
kubectl exec -n ${NAMESPACE} $pod -c $con -- $c > ${EXECDIR}/$con/$j
fi
This seems to be working for me.

Loop each file and check file size

I am using Github Action to run pylint, I have a list of modified files and need to check if they are blank or not, if they are blank then skip them, how do I do this?
Part of Action:
- name: Get modified files
id: files
uses: umani/changed-files#v3.3.0
with:
repo-token: ${{ github.token }}
pattern: '^src.*\.(py)$'
result-encoding: 'string'
- name: Check files size
id: file_check
run: |
echo "file_size="$(printf "%s" "${{ steps.files.outputs.files_updated }} ${{ steps.files.outputs.files_created }}" | wc -m) >> $GITHUB_ENV
echo 'MESSAGE=No valid file found, skipped' >> $GITHUB_ENV
- name: Lint with pylint
if: env.file_size > 1
working-directory: ./
run: |
pip install pylint
OUTPUT=$(pylint ${{ steps.files.outputs.files_updated }} ${{ steps.files.outputs.files_created }} --exit-zero --jobs=0 --rcfile=.pylintrc)
LAST_LINE=$(tail -1 <<< "$OUTPUT")
SCORE=$(sed -n '$s/[^0-9-]*\([-0-9.]*\).*/\1/p' <<< "$OUTPUT")
OUTPUT=$(echo "$OUTPUT" | sed -e '20{$!N;s/\n.*/\n\n\n... results too long, run pylint locally to get full result/' -e 'q}')
OUTPUT+=". Pylint finished with score: $SCORE"
echo "SCORE=$SCORE" >> $GITHUB_ENV
echo 'MESSAGE<<EOF' >> $GITHUB_ENV
echo "$OUTPUT" >> $GITHUB_ENV
echo 'EOF' >> $GITHUB_ENV
So what I need to do is loop the variables ${{ steps.files.outputs.files_updated }} ${{ steps.files.outputs.files_created }}" which are currently encoded as comma separated strings. And check if that file is blank or not, then create a new list with non-blank files, how do I do this?
You can try something like this
IFS=, read -a fa <<<"${{ steps.files.outputs.files_updated }}"
declare -a fe fne
for f in "${fa[#]}"
do
if [[ -s "$f" ]]
then
fne+=( "$f" )
else
fe+=( "$f" )
fi
done
# fne: non-empty files
# fe: empty files

Execute bash script via ansible playbook

I'm looking to run the following shell script via ansible playbook.
#!/bin/bash
oci compute instance list --lifecycle-state RUNNING --region ca-toronto-1 --compartment-id < compartment OCID> --all | grep display-name -A 0 > hostnames.txt
for line in `cat hostnames.txt`
do
#echo $line
if [[ $line == *","* ]]; then
# hostname=$(echo ${line//"display-name"/} | tr -d '",: ')
hostname=$(echo "$line" | tr -d '",')
echo "$hostname"
ssh -tt "$hostname" "sudo puppet agent -tv && sleep 10"
# break
fi
done
This works just like how i want when i run the shell script but I get a blank output when i run via ansible.
Playbook:
---
- name: puppet agent trigger
gather_facts: false
become_user: true
hosts: all
tasks:
- name: trigger puppet agent
shell: |
oci compute instance list --lifecycle-state RUNNING --region ca-toronto-1 --compartment-id <compartment OCID> --all | grep display-name -A 0 > hostnames.txt
for line in `cat hostnames.txt`
do
if [[ $line == *","* ]]; then
hostname=$(echo "$line" | tr -d '",')
echo "$hostname"
ssh -tt "$hostname" "sudo puppet agent -tv && sleep 10"
fi
done
register: shell_output
- debug:
msg: "{{ shell_output.stdout }}"
Please point me as to what im missing.
According the description of your use case it seems to be recommended to transfer the whole logic of the script into Ansible itself. To do so and in respect to the comment regarding add_host_module, you could use an approach like
- name: Create an instance list
shell:
cmd: oc get nodes --no-headers | cut -d " " -f 1 | tr '\n' "," | rev | cut -c 2- | rev
register: instance_list
changed_when: false
To generate the instance_list I've used an OpenShift cluster as example, because I don't have something like oci compute instance list ... accessible.
- name: Add all hosts from instance_list to the script group
add_host:
name: '{{ item }}'
groups: script
loop: "{{ instance_list }}"
From there you could proceed further to execute your command puppet agent -tv && sleep 10.

Need to refer from first register variable to second variable using only the index number

I have two register variables, I loop on the first one and I need to loop on the second using only the index number.
I put this {{y.results[0].stdout}} but of course it only stay on the first array.
I want to loop on register y the same as register x index number.
- shell: |
if [[ $(fdisk -l /dev/{{raw_prefix}}{{item}} | grep '/dev/{{raw_prefix}}{{item}}{{partition}}' | wc -l) = 0 ]]; then fdisk -l /dev/{{raw_prefix}}{{item}} | grep 'Disk /dev' | awk '{print $3}' ; fi
ignore_errors: true
register: x
with_items: "{{letters}}"
- shell: |
if [[ $(fdisk -l /dev/{{raw_prefix}}{{item}} | grep '/dev/{{raw_prefix}}{{item}}{{partition}}' | wc -l) = 0 ]]; then fdisk -l /dev/{{raw_prefix}}{{item}} | grep 'Disk /dev' | awk '{print $4}' ; fi
ignore_errors: true
register: y
with_items: "{{letters}}"
- shell: echo {{item.stdout}} - {{y.results[????].stdout}}
with_items: "{{x.results}}"
For example:
x[0].stdout=10 y[0].stdout=MB
x[1].stdout=5 y[1].stdout=GB
So the output should be:
10 - MB
5 - GB
Basically I'm creating a partitioning playbook so that I could determine a raw disk 10GB.
If you are just interested in the output change your if statement, use awk 'OFS=" - "; {print $3, $4}'. No need to register x and y. One task will provide the required output.
- shell: |
if [[ $(fdisk -l /dev/{{raw_prefix}}{{item}} | grep '/dev/{{raw_prefix}}{{item}}{{partition}}' | wc -l) = 0 ]]; then fdisk -l /dev/{{raw_prefix}}{{item}} | grep 'Disk /dev' | awk 'OFS=" - "; {print $3, $4}' ; fi
ignore_errors: true
with_items: "{{letters}}"
I know that but what I'm trying to do is to loop from sdb up to sdx, u don't know how many disk are there. So to capture all the 10 (awk $3) you have to fdisk -l (compatible with all version of redhat), so i need also to capture GB (awk $4). But I figured out that this is hard. So I can't do it with_items looping, I will do is to hard code it like,
shell: echo {{x.results[0].item.stdout}} - {{y.results[0].stdout}} >> {{pre_check_logs}}
shell: echo {{x.results[1].item.stdout}} - {{y.results[1].stdout}} >> {{pre_check_logs}}
By the way this is github,
https://github.com/rv-ansible/disk_mgnt.git

Ansible: escape quotes and listing users password expiry information

How to escape in shell module quotation?
I've tried as follows:
- name: UList
shell: "cut -f 1 -d: /etc/passwd | sudo xargs -n 1 -I {} bash -c \" echo {} ; chage -l {}\""
and
- name: UList
shell: "cut -f 1 -d: /etc/passwd | sudo xargs -n 1 -I {} bash -c \' echo {} ; chage -l {}\'"
Where is a mistake?
This playbook worked for me, hope this will be helpful for you too. You can use single quotes' for a command if you have an issue escaping " quote
Either do it this way
'cut -f 1 -d: /etc/passwd | sudo xargs -n 1 -I {} bash -c " echo {} ; chage -l {}"'
Or
"cut -f 1 -d: /etc/passwd | sudo xargs -n 1 -I {} bash -c ' echo {} ; chage -l {}'"
Both are working i have tested it.
---
- name: Set my hosts variable
hosts: localhost
tasks:
- name: UList
shell: 'cut -f 1 -d: /etc/passwd | sudo xargs -n 1 -I {} bash -c " echo {} ; chage -l {}"'
register: result
- name: debug
debug:
msg: "{{result}}"
Or
For the output you are expecting for that you can use
awk -F':' '{ system("echo " $1 " && chage -l " $1) }' /etc/passwd
Command explanation
---
- name: Set my hosts variable
hosts: localhost
tasks:
- name: UList
shell: "awk -F':' '{ system(\"echo \" $1 \" && chage -l \" $1) }' /etc/passwd"
register: result
- name: debug
debug:
msg: "{{result}}"

Resources