how to use with_items register.results - ansible

I'm currently running a command as follows:
- name: "1. search directory"
shell: find /var/ -name "directory"
register: directoty
- name: "boucle"
debug:
msg: "{{item}}"
with_items: "{{directory.stdout_lines}}"
- name: "2. check existance of file"
stat:
path: "{{item}}/file.log"
with_items: "{{directory.stdout_lines}}"
register: checkfile
- debug:
msg: "file name {{item}} exists"
with_items: {{checkfile.results}}
when: checkfile.stat.exists
when i launch it i have error:
with_items: \"{{checkfile.results}}\"\n ^ here\nWe could be wrong, but this one looks like it might be an issue with\nmissing quotes. Always quote template expression brackets when they\nstart a value. For instance:\n\n with_items:\n - {{ foo }}\n\nShould be written as:\n\n with_items:\n - \"{{ foo }}\"\n"}
what can i do to use with_items with stat register

There are a few issues with your last task.
Add quotes " to the with_items: parameter value
Use item in the when: parameter
Use consistent spacing in YAML files (i.e. 2 space indentations)
Example below:
- name: "2. check existance of file"
stat:
path: "{{item}}/file.log"
with_items: "{{directory.stdout_lines}}"
register: checkfile
- debug:
msg: "file name {{item}} exists"
with_items: "{{checkfile.results}}"
when: item.stat.exists

Related

yaml syntactical error with_items loop with a list

trying to loop with a list to create a append a yaml file; getting some syntactical error ?
any idea how we can fix this ?
- name: "append yml"
shell: echo "instances:\n\n - name: all\n - command: all\n - arguments:\n - cluster_name: dbtype{{ item }} all\n - host: {{ipv4}}\n" >> /path/dbtype-config.yml
shell: echo " - auth_source: admin\n - ssl: false\n - ssl_insecure_skip_verify: false\n - labels:\n - env: env\n" >> /tmp/newrelic-infra/integrations.d/dbtype-config.yml
with_items: "{{ instances.stdout_lines }}"
ERROR! Syntax Error while loading YAML.
The error appears to have been in '/ansible/projects/newrelic/dbtype_nr.yml': line 27, column 47, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: "update yml"
shell: echo "instances:\n\n - name: all\n - command: all\n - arguments:\n - cluster_name: dbtype{{ item }} all\n - host: {{ipv4}}\n" >> /path/dbtype-config.yml
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
looks like it's something similar to #Unknown's suggestion, put single quotes around the : inside of the echo.
Also, are you certain two shell commands will work inside of the single task? I would make two tasks, like:
- name: "append 1st yml"
shell: echo 'first part'
with_items: "{{ my_list }}"
- name: "append 2nd yml"
shell: echo 'second part'
with_items: "{{ my_list }}"

ansible "with_lines: cat somefile" fails in a skipped block

I have a playbook with a block that has a when condition. Inside is a task with a loop. How can I change this loop so that when the condition is false the skipped task doesn't fail?
block:
- name: create a file
lineinfile:
line: "Hello World"
path: "{{my_testfile}}"
create: yes
- name: use the file
debug:
msg: "{{ item}}"
with_lines: cat "{{my_testfile}}"
when: false
TASK [create a file] ************************************************************************************************************************************************************
TASK [use the file] *************************************************************************************************************************************************************
cat: files/my/testfile: No such file or directory
fatal: [ipad-icpi01]: FAILED! => {"msg": "lookup_plugin.lines(cat \"files/mytestfile\") returned 1"}
Change your failing task to the following which will always be able to run, even if the file does not exists, and will not use the shell or command where there is no need to:
- name: use the file
debug:
msg: "{{ item }}"
loop: "{{ (lookup('file', my_testfile, errors='ignore') | default('', true)).split('\n') }}"
The key points:
use the file lookup plugin with errors='ignore' so that it returns the file content or None rather than an error when file does not exists.
use the default filter with second option to true so that it return default value if var exists but is null or empty.
split the result on new lines to get a list of lines (empty list if file does not exist).
Note: as reported by #Vladimir, I corrected your var name which is not valid in ansible.
Test the existence of the file. For example
- block:
- name: create a file
lineinfile:
line: "Hello World"
path: "{{ my_testfile }}"
create: yes
- name: use the file
shell: '[ -f "{{ my_testfile }}" ] && cat {{ my_testfile }}'
register: result
- name: use the file
debug:
msg: "{{ item }}"
loop: "{{ result.stdout_lines }}"
when: false
The lookup plugin file should be preferred.
I ended up with a mix of the provided answers. These tasks will be skipped without failing or creating a warning.
- block:
- name: create a file
lineinfile:
line: "Hello World"
path: "{{ my_testfile }}"
create: yes
- name: get the file
slurp:
src: "{{ my_testfile }}"
register: result
- name: use the file
debug:
msg: "{{ item }}"
loop: "{{ (result['content'] | b64decode).split('\n') }}"
when: false

I tried to use "with_items" inside when statement but failed

- hosts: 22rrvgndns01
gather_facts: no
vars_files:
- /etc/ansible/dnschange/dns_resource_record.yml
tasks:
- shell: grep "{{item.name}}" check_result.txt
args:
chdir: /cluster/dnschange
when: "{{item.action}}" is match("delete")
with_items: "{{resource_record}}"
Here is the resource_record:
- resource_record:
- name: test.201.apn.epc.mnc002.mcc505.3gppnetwork.org
record_type: naptr
action: create
view: MME
ttl: 300
order: 100
preference: 999
flags: s
service: x-3gpp-pgw:x-gn:x-gp:x-s5-gtp
replacement: wip-ows-pgw-e-NSW.node.epc.mnc002.mcc505.3gppnetwork.org
I got the error when I executed the script
The offending line appears to be:
chdir: /cluster/dnschange
when: "{{item.action}}" is match("delete")
^ here
I could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
Can anyone help me out?
I guess your indentation is wrong and change in when condition. Can you try as below
- shell: grep "{{item.name}}" check_result.txt
args:
chdir: /cluster/dnschange
when: item.action == 'delete'
with_items: "{{resource_record}}"

In Ansible ,can we loop through list of files and match content in file using lineinfile module

I have to find all config.xml on a server and produce the list on a given server.
Once we registered the files list, i have to check the content in each file on the list using Ansible
I tried to derive the paths for all config.xml
register them and print the list
Added the registered variable into lineinfile path
##Derive Config.xml path
- name: Find the location of xml file
shell: find {{ wlx_mount_point }} -maxdepth 1 -name {{xml_file}} | rev | cut -d '/' -f3- | rev
register: wlx_domain_home
ignore_errors: yes
- debug:
msg: "{{ wlx_domain_home.stdout_lines|list }}"
- name: check domain home directory exists
stat:
path: "{{ wlx_domain_home |list }}"
ignore_errors: true
- debug:
msg: "{{ wlx_domain_home.stdout_lines|list }}"
- name: "Ensure Logging Settings in config.xml"
lineinfile:
line: "{{ item.line }}"
regexp: "{{ item.regexp }}"
path: "{{ wlx_domain_home.stdout_lines|list }}/config/config.xml"
state: present
backrefs: yes
register: config.xml.Logging
with_fileglob: "{{ wlx_domain_home.stdout_lines|list }}/config/config.xml"
with_items:
- line: "<logger-severity>Info</logger-severity>"
regexp: "^logger-severity.*"
Expected results are , it has to look for lines in each file and loop through the list. ` Its printing the list and not able to find the content
"_ansible_ignore_errors": true, "msg": "Destination
[u'/appl/cmpas9/user_projects/pte-ipscasws',
u'/appl/bbb/user_projects/qa-ucxservices_bkp',
u'/appl/app/user_projects/weiss_apps12',
u'appl/view/user_projects/weiss_apps12_oldbkp',
u'appl/voc/user_projects/qa-voc']/config/config.xml does not exist !"
}
This is how i fixed the issue. Now it gives output
- name: find all weblogic domain paths
shell: find /tech/appl -type f -name config.xml
register: wlx_domain_config
- debug:
var: wlx_domain_config.stdout_lines
name: "Ensure allow-unencrypted-null-cipher Encryption Settings in config.xml"
shell: grep -i "" {{ item }}
with_items: "{{ wlx_domain_config.stdout_lines }}"
register: allowunencrypted
debug:
var: allowunencrypted.stdout_lines

How to register with_items and act on conditional check result for each item

I'd like to register the contents of bashrc for two users and edit as/if required. My play is as follows.
- name: Check bashrc
shell: cat {{ item }}/.bashrc
register: bashrc
with_items:
- "{{ nodepool_home }}"
- "{{ zuul_home }}"
- name: Configure bashrc
shell:
cmd: |
cat >> {{ item }}/.bashrc <<EOF
STUFF
EOF
with_items:
- "{{ nodepool_home }}"
- "{{ zuul_home }}"
when: '"STUFF" not in bashrc.stdout'
It fails as follows:
fatal: [ca-o3lscizuul]: FAILED! => {"failed": true, "msg": "The conditional check '\"STUFF\" not in bashrc.stdout' failed. The error was: error while evaluating conditional (\"STUFF\" not in bashrc.stdout): Unable to look up a name or access an attribute in template string ({% if \"STUFF\" not in bashrc.stdout %} True {% else %} False {% endif %}).\nMake sure your variable name does not contain invalid characters like '-': argument of type 'StrictUndefined' is not iterable\n\nThe error appears to have been in '/root/openstack-ci/infrastructure-setup/staging/zuul/create-user.yml': line 35, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Configure bashrc\n ^ here\n"}
I think, if I understand your requirement correctly, you can use the 'lineinfile' or 'blockinfile' modules and save yourself the hassle of testing for the existence of the content:
- name: Noddy example data
set_fact:
single_line: "STUFF"
multi_line: |
STUFF
STUFF
profile_dirs:
- "{{ nodepool_home }}"
- "{{ zuul_home }}"
- name: Ensure STUFF exists in file
lineinfile:
path: "{{ item }}/.bashrc"
line: "{{ single_line }}"
loop: "{{ profile_dirs }}"
- name: Ensure block of STUFF exists in file
blockinfile:
path: "{{ item }}/.bashrc"
block: "{{ multi_line }}"
loop: "{{ profile_dirs }}"
Both modules give a lot more control and you can find their docs here: lineinfile | blockinfile

Resources