Ansible judgment file directory - bash

I want to do such a thing.In the presence of directory skip, otherwise will be created.
For example:
#!/bin/bash
for $i in 'a.test.com a.test.com c.test.com'
do
if [ ! -e $i ]:
then
mkdir $i
fi
done
How to use ansible-playbook implement the above code.
thanks

Looks like simple directory creation using the file module in a loop.
- name: make sure subdomain directories exist
file: path=/opt/{{item}} state=directory recursive=yes
with_items:
- a.test.com
- b.test.com
- c.test.com

If the directory is created, or skip.
- name: test log dir
shell: "test -e /data/{{item[0]}}/{{item[1]}} -o -h /data/{{item[0]}}/{{item[1]}}"
ignore_errors: True
with_nested:
- ['logs', 'html']
- ['a.test.com', 'b.test.com']
register: dir_stats
tags: check_log
- name: create log dir
file: path=/data/{{item.item[0]}}/{{item.item[1]}} state=directory owner=apache group=apache recursive=yes
with_items: dir_stats.results
when: item.rc != 0
tags: check_log

Related

how to do a successful exit from the playbook task

I have a playbook which is repeating one task, shell is invoked from ansible task, but it does not exit successful on completion of task and repeating the shell instructions again.
Playbook:
---
hosts: dev-servers
tasks:
- name: clean up directoty
shell: rm -rf /opt/data/latest/*
- name: copy the file
copy: src=/home/data/metadata.zip dest=/opt/data
- name: Change directoty
shell: cd /opt/data
- name: copy the file
copy: src=/root/Run_Build.sh dest=/opt/deployment_scripts
- name: permission
shell: chmod +x /opt/deployment_scripts/Run_Build.sh
- name: deploy
command: sh /opt/deployment_scripts/Run_Build.sh
run_once: true
register: result
- debug: msg="{{ result.stdout }}"
- debug: msg="{{ result.stderr }}"
Run_Build.sh:
#!/bin/bash
Jboss_logs=/opt/jboss/jboss-eap-6.4/standalone/log/server.log
for i in {1..100}; do
sleep 10
if [ -f $Jboss_logs/server.log ]; then
if grep -e 'Deployed "deploy.war"' $Jboss_logs/server.log ; then
echo "Code successfully deployed"
exit 0
else
echo "*****************************************************************************"
echo " JBOSS is still loading deployment - please be patient .... Loading again in 10 sec"
echo "*****************************************************************************"
fi
else
echo "server log file has not been created yet, please wait for sometime."
fi
done

Change several files with specific file extension to another extension in a folder

In a folder containing files with different extensions (*.rules and *.rules.yml), I need to change the file extension based on certain condition:
*.rules => *.rules.yml, or
*.rules.yml => *.rules
In shell, I can do it as:
Case # 1
for file in ./*.rules; do mv "$file" "${file%.*}.rules.yml" ; done
# from *.rules to *.rules.yml
Case # 2
for file in ./*.rules.yml ; do mv "$file" "${file%.*.*}.rules" ; done
# from *.rules.yml to *.rules
Any idea in ansible to do the same thing?
Any help will be appreciated :)
Assuming the difficulty you are having is with YAML quoting, you may experience better luck with the "pipe literal":
tasks:
- shell: |
for i in *.rules; do
/bin/mv -iv "$i" "`basename "$i" .rules`.rules.yml"
done
- shell: |
for i in *.rules.yml; do
/bin/mv -v "$i" "`basename "$i" .rules.yml`.rules"
done
One will also notice that I used the more traditional basename rather than trying to do "crafty" variable expansion tricks, since with it should run with any posix shell.
Or if you are experiencing that your target system uses dash, or zsh, or ksh, or whatever, you can also be explicit in the shell you wish for ansible to use:
tasks:
- shell: echo "hello from bash"
args:
executable: /bin/bash
Thanks for the help, Matthew L Daniel. It works quite well.
The final working solution would be enclosed as reference:
- name: Run in local to replace suffix in a folder
hosts: 127.0.0.1
connection: local
vars:
- tmpRulePath: "rules"
- version: "18.06" # change the version here to change the suffix from rules/rules.yml to rules.yml/rules
- validSuffix: "rules.yml"
- invalidSuffix: "rules"
tasks:
- name: Prepare the testing resources
shell: mkdir -p {{ tmpRulePath }}; cd {{ tmpRulePath }}; touch 1.rules 2.rules 3.rules.yml 4.rules.yml; cd -; ls {{ tmpRulePath }};
register: result
- debug:
msg: "{{ result.stdout_lines }}"
- name: Check whether it's old or not
shell: if [ {{ version }} \< '18.06' ]; then echo 'true'; else echo 'false'; fi
register: result
- debug:
msg: "Is {{ version }} less than 18.06 {{ result.stdout }}"
- name: Update validSuffix and invalidSuffix
set_fact:
validSuffix="rules"
invalidSuffix="rules.yml"
when: result.stdout == "true"
- debug:
msg: "validSuffix is {{ validSuffix }} while invalidSuffix {{ invalidSuffix }}"
- name: Replace the invalid suffix with valid
shell: |
cd {{ tmpRulePath }};
for i in *.{{ invalidSuffix }}; do
/bin/mv -v "$i" "`basename "$i" .{{ invalidSuffix }}`.{{ validSuffix }}"
done
- name: Check the latest files
shell: ls {{ tmpRulePath }}
register: result
- debug:
msg: "{{ result.stdout_lines }}"
- name: Clean up
shell: rm -rf {{ tmpRulePath }}

for loop not working with ansible shell module

I am trying to check group ownership of all the directory named "deployments" inside path. To do this I am using for loop with find command and store all the deployments dir in variable. And then using grep I am checking whether there is any deviation. Below is my task. The problem is that the Its not working and even if group ownership is different its not detecting it.
How can i check and fix how the command i am passing in shell module is running correctly by shell module.
---
- name: deployment dir group ownership check
shell: for i in `find /{{ path }} -name deployments -type d -print`;do ls -ld $i | grep -v 'sag';done > /dev/null 2>&1; echo $?
register: find_result
delegate_to: "{{ pub_server }}"
changed_when: False
ignore_errors: true
tags:
- deployment_dir
- debug: var=find_result
- name: status of the group in deployments dir
shell: echo "Success:Deployments dir is owned by sag group in {{ path }} in server {{ pub_server }}" >> groupCheck.log
when: find_result.stdout == "1"
changed_when: False
tags:
- deployment_dir
- name: status of the group in deployments dir
shell: echo "Fail:Deployments dir is NOT owned by sag group in {{ path }} in server {{ pub_server }}" >> groupCheck.log
changed_when: False
when: find_result.stdout == "0"
tags:
- deployment_dir
Why you use that shell with find?
You can stat the folder and then get the UID and GID for set those permissions...
---
- hosts: localhost
gather_facts: no
connection: local
tasks:
- stat:
path: /tmp
register: tmp
- debug: msg="Uid {{ tmp.stat.uid }} - Guid {{ tmp.stat.gid }}"
Playbook run:
PLAY ***************************************************************************
TASK [stat] ********************************************************************
ok: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "Uid 0 - Guid 0"
}
Tmp folder:
14:17:17 kelson#local:/# ls -la /
drwxrwxrwt 23 root root 4096 Mai 14 14:17 tmp
Using that line of thinking, you can use the find module, register the output and use stat with your results to seek every folder permissions or set those you want...

ansible overwrite variable depending on result

I am running several shell commands in an ansible playbook that may or may not modify a configuration file.
One of the items in the playbook is to restart the service. But I only want to do this if a variable is set.
I am planning on registering a result in each of the shell tasks, but I do not want to overwrite the variable if it is already set to 'restart_needed' or something like that.
The idea is the restart should be the last thing to go, and if any of the commands set the restart variable, it will go, and if none of them did, the service will not be restarted. Here is an example of what I have so far...
tasks:
- name: Make a backup copy of file
copy: src={{ file_path }} dest={{ file_path }}.{{ date }} remote_src=true owner=root group=root mode=644 backup=yes
- name: get list of items
shell: |
grep <file>
register: result
- name: output will be 'restart_needed'
shell: |
NUM=14"s"; if [ "${NUM}" != "s" ]; then sed -i "${NUM}/no/yes/g" {{ file_path }}; echo "restart_needed"; else echo "nothing_changed" ; fi
with_items: "{{ result.stdout_lines }}"
register: output
- name: output will be 'nothing_changed'
shell: |
NUM="s"; if [ "${NUM}" != "s" ]; then sed -i "${NUM}/no/yes/g" {{ file_path }}; echo "restart_needed"; else echo "nothing_changed" ;; fi
with_items: "{{ result.stdout_lines }}"
register: output
- name: Restart service
service: name=myservice enabled=yes state=restarted
In the above example, the variable output will be set to restart_needed after the first task but then will be changed to 'nothing_changed' in the second task.
I want to keep the variable at 'restart_needed' if it is already there and then kick off the restart service task only if the variable is set to restart_needed.
Thanks!
For triggering restarts, you have two options: the when statement or handlers.
When statement example:
tasks:
- name: check if string "foo" exists in somefile
shell: grep -q foo somefile
register: result
- name: restart service
service:
name: myservice
enabled: yes
state: restarted
when: result.rc == 0
Handlers example:
tasks:
- name: check if string "foo" exists in somefile
shell: grep -q foo somefile
register: result
changed_when: "result.rc == 0"
notify: restart service
handlers:
- name: restart service
service:
name: myservice
enabled: yes
state: restarted

how to make excluded variables dynamic in ansible

i am trying to make a playbook to change permissions across all servers, but i need to exclude few directories and files. I am trying to make the files allocation dynamic , as you can see i have excluded 2 , but i want to make it generalized or dynamic . plz suggest .
Below is my playbook, please note i am using directory structure :
permission.yml:
---
- hosts: 127.0.0.1
roles:
- { role: fileperm, target_dir: "/tmp/testingpermissions" }
- { role: fileperm, target_dir: "/tmp/abc" }
- { role: fileperm, target_dir: "/amp/app/tomcatdefault7055" }
Vars:
main.yml:
---
exclude1: "/tmp/testingpermissions/plugins"
exclude2: "/tmp/testingpermissions/files"
tasks:
main.yml:
---
- name: Ensure directories are 0755
command: find {{ target_dir }} -type d ! -path "{{ exclude1 }}*" ! -path "{{ exclude2 }}*" -exec chmod -c 0755 {} \;
register: chmod_result
changed_when: "chmod_result.stdout != \"\""
You could use the 'file' module, and loop through your list of directories that need to have their permissions changed,
e.g. sth like this in the vars:
# /vars/main.yml
updatepermissions:
- "/tmp/testingpermissions"
- "/tmp/abc"
- "/amp/app/tomcatdefault7055"
... and then sth like this in the tasks:
# /tasks/main.yml
- name: Set directory permissions to 0755
file:
path: "{{ item }}"
state: directory
mode: 0755
with_items: "{{ updatepermissions }}"
This will set the permissions on only the directories that you specify. So instead updating permissions for everything except for some excluded few, you'd only update the permissions on a set list of directories that need the given permissions.
For directories where you don't want to exclude any subdirectories from setting permissions, you can add "recurse=yes".
Otherwise, if you prefer the command task with "! -path", you could maybe do something like this:
# /vars/main.yml
updatepermissions:
- include: "/tmp/testingpermissions"
exclude: "! -path \"/tmp/testingpermissions/plugins\" ! -path \"/tmp/testingpermissions/abc\""
- include: "/some/other/directory"
exclude: ""
and then in the tasks sth like this:
# /tasks/main.yml
- name: update permissions
command: "find {{ item.include }} -type d {{ item.exclude }} -exec chmod -c 0755 {} \;"
register: chmod_result
changed_when: "chmod_result.stdout != \"\""
with_items: "{{ updatepermissions }}"

Resources