Ansible Standard Loop Not working - ansible

I have written the following ansible script
---
# Playbook file: loopplay.yml
-
name: loopplay
hosts: centos2
tags:
- loopplay
tasks:
-
name: looptask
user:
name: "{{ item }}"
state: present
groups: "wheel"
loop:
- testuser1
- testuser2
However, I keep on getting the following error:
The error appears to have been in
'/opt/ansible-projects/test_5af9a55448f0c8003531a07d_loopproject/loopplay.yml':
line 10, column 13, but may be elsewhere in the file depending on the
exact syntax problem.
The offending line appears to be:
name: looptask ^ here
Can someone let me know where I might be going wrong?

you should fix the indentation first.
here is a sample yml to get you started fixing your own:
- name: loopplay
hosts: localhost
tags:
- loopplay
tasks:
- name: print something
debug:
msg: "test msg"

Related

Ansible playbook conditionals

I'm trying to put together playbook that works for both Windows and Linux. Now I'm trying to include roles in playbook that will be taken only if Windows or Linux, but it always complains about syntax. I'd appreciate any help on this as I've tried few different approaches and it always failed.
---
- hosts: all
gather_facts: no
pre_tasks:
- name: (localhost) make sure the known_hosts file is cleared
lineinfile:
path: ~/.ssh/known_hosts
state: absent
regexp: "^{{ ansible_host | replace('.', '\\.') }}.*$"
delegate_to: 127.0.0.1
- hosts: all
serial: 1
pre_tasks:
- name: (debug) print out some debug message to confirm inventory is properly set up
debug:
msg: "System inventory_hostname:{{ inventory_hostname }} ansible_host:{{ ansible_host }}"
- hosts: all
tasks:
- name: Install CA Trust Certs Windows
include_tasks: tasks\install-certs-windows.yml
when: ansible_os_family == 'Windows'
- name: Install CA Trust Certs Linux
include_tasks: tasks/install-certs-linux.yml
when: ansible_os_family != 'Windows'
roles:
- { role: ansible-role-runnersbasics, tags: ["basics"] }
- { role: ansible-role-docker, tags: ["docker"] }
- { role: ansible-role-gitlab-runner }
when: ansible_os_family == 'Windows'
Error:
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)
Syntax Error while loading YAML.
did not find expected key
The error appears to be in 'playbook.yml': line 33, column 5, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- { role: ansible-role-gitlab-runner }
when: ansible_os_family == 'Windows'
^ here
When removing curly braces from roles and moving when on the same level as roles
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)
Syntax Error while loading YAML.
mapping values are not allowed in this context
The error appears to be in 'playbook.yml': line 30, column 43, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
roles:
role: ansible-role-runnersbasics, tags: ["basics"] }
^ here
In a word: DON'T
Alright, that's two words if you want to get picky about contractions.
Anyway.... Group your servers by OS, then work on them separately:
---
- hosts: Linux
gather_facts: no
# Do Linux stuff
- hosts: Windoze
serial: 1
# Do Windoze stuff
Resolved by using method that #Khaled provided (thanks again!)
roles:
- role: ansible-role-runnersbasics
tags: ["basics"]
when: ansible_os_family == 'Windows'

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}}"

Syntax to pass dynamic variables to include_tasks along with with_item in Ansible playbook

Executing parent.yml which in turn calls child.yml playbook for execution with dynamic variables.
Variables from parent.yml aren`t interpolated inside child.yml playbook. Correct me if I am using correct syntax?
Parent.yml
- name: Main playbook to call MySQL backup
hosts: localhost
gather_facts: no
tasks:
- include_task: child.yml
vars:
var1: "{{ item.name }}"
var2: "{{ item.db_name }}"
with_items:
- { name: '10.10.10.01', db_name: 'prod1' }
- { name: '10.10.10.02', db_name: 'prod2' }
child.yml (Takes mysqldump from managed DB)
- name: MySQL dump
hosts: localhost
#gather_facts: no
#vars:
# v1: "{{ var1 }}"
# v2: "{{ var2 }}"
tasks:
- name: Executing the shell script
shell: 'mysqldump -h "{{ var1 }}" -u"ansi" -p"*****" "{{ var2 }}"| gzip > /tmp/mysql_dump/"{{ var2 }}"_`date +%Y%m%d-%H%M`.gz'
fatal: [127.0.0.1]: FAILED! => {"reason": "no action detected in task. This often indicates a misspelled module name, or incorrect module path.\n\nThe error appears to be in '/home/ansible/playbooks/DBpatch/Linux/child.yml': line 1, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: MySQL dump\n ^ here\n"}
include_task expects a list of tasks but you give it a complete playbook.
Child.yml should only contain what is currently below the line "tasks:".
See also https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_includes.html

ansible reading variable from json file

i am new to ansible world. trying to providing all variable from json file, but its not accepting. it shows and error variable undefined
below is my json file
{
"Tomcat":{
"SHPN":"8905",
"HTPN":"8980",
"SSPN":"8943",
"AJPN":"8909",
"Server":"test.example.com",
"JENKINS_HOME":"/apps/tech/jenkins/jenkins-configuration",
"PName":"Tomcat-Installation",
"IName":"ansible_test",
"IUID":"jbosscfg",
"IGID":"staff",
"IDEPT":"tech",
"IRECPT":"test#example.com"
}
}
below is my playbook
---
-
gather_facts: false
hosts: "{{Server}}"
tasks:
-
ignore_errors: true
name: "find no of Tomcat Instance available on the Server"
copy:
src: "{{ JENKINS_HOME }}/workspace/{{ PName }}/instance/"
dest: /apps/tech/{{IName}}
group: "{{IGID}}"
owner: "{{IUID}}"
mode: 0755
-
replace: "dest='/apps/tech/{{IName}}/scripts/set_env.sh' regexp='<DEPARTMENT NAME>' replace='{{IDEPT}}'"
-
replace: "dest='/apps/tech/{{IName}}/scripts/set_env.sh' regexp='<RECIPIENT>' replace='{{IRECPT}}'"
-
replace: "dest='/apps/tech/{{IName}}/scripts/set_env.sh' regexp='<TOMCAT INSTANCE NAME>' replace='{{IName}}'"
-
replace: "dest='/apps/tech/{{IName}}/scripts/set_env.sh' regexp='<USER ID>' replace='{{IUID}}'"
-
name: "Ansible Template Example"
template:
src: tomcat_server.j2
dest: /apps/tech/{{IName}}/conf/server.xml
mode: 0777
i am below while executing the ansible playbook - error says variable undefined
test.example.com:~/final:$ ansible-playbook configure-tomcat-instance.yml --extra-vars "#test.json"
ERROR! the field 'hosts' has an invalid value, which appears to include a variable that is undefined. The error was: 'Server' is undefined
The error appears to have been in '/home/jbosscfg/final/configure-tomcat-instance.yml': line 3, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
-
gather_facts: false
^ here
You refer variables as if they are at the top level, whereas they are under Tomcat key.
Use hosts: "{{Tomcat.Server}}" or reformat your json file to eliminate Tomcat level.

Registering multiple variables in a loop

I have a variable yaml file:
---
apps:
- client
- node
- gateway
- ic
- consul
and this task:
- name: register if apps exists
stat: path="/etc/init.d/{{ item }}"
with_items: apps
register: "{{ item.stat.exists }}exists"
I need to end up with a variable for each app with a value of true or false whether the file exists or not:
clientexists = true
nodeexists = true
gatewayexists = false
icexists = true
consulexists = false
For some reason, the item and exists concat is not working.
How can I achieve that??
Try this hope this will help you out. While looping in Stats.yml then msg field will contain your desired output.
Variables.yml Here we are defining variables
---
apps:
- client
- node
- gateway
- ic
- consul
Stats.yml
---
- hosts: localhost
name: Gathering facts
vars_files:
- /path/to/variables.yml
tasks:
- name: "Here we are printing variables"
debug:
msg: "{{apps}}"
- name: "Here we are gathering stats and registering it"
stat:
path: "/etc/init.d/{{item}}"
register: folder_stats
with_items:
- "{{apps}}"
- name: "Looping over registered variables, Its msg field will contain desired output"
debug:
msg: "{{item.invocation.module_args.path}}: {{item.stat.exists}}"
with_items:
- "{{folder_stats.results}}"
...
folder_stats will contain whole result, for individually referring to single - single result You can use it like this in you playbook.
folder_stats.results[0].stat.exists
folder_stats.results[1].stat.exists
folder_stats.results[2].stat.exists
folder_stats.results[3].stat.exists

Resources