When using ansible for automating operations, it is unavoidable to repeat certain operations, such as adding several users, creating several MySQL users and giving them permissions, manipulating all files in a directory, and so on. Fortunately, the Playbook supports loop statements, which makes certain requirements very easy and prescriptive to implement.
1, With_items
With_items is the most basic and most commonly used looping statement in playbooks:
Tasks
-Name:secure config files
file:path=/etc/{{Item}} mode=0600 owner=root Group=root
With_items:
-MY.CNF
-Shadow
-Fstab
The above example shows that three files were created for my.cnf, shadow, Fstab
You can also assign a file list to a variable in advance, and then call it in a looping statement:
with_items:
"{{ somelist }}"
使用with_items迭代循环的变量可以是个单纯的列表,也可以是一个较为复杂 的数据结果,如字典类型:
tasks:
- name: add several users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: ‘testuser1‘, groups: ‘wheel‘ }
- { name: ‘testuser2‘, groups: ‘root‘ }
2、with_nested嵌套循环
Example:
Tasks
-Name:give users access to multiple databases
mysql_user:name={{item[0]}} priv={{item[1]}}.*:all append_privs=yes Password=foo
With_nested:
-[' Alice ', ' Bob ']
-[' Clientdb ', ' employeedb ', ' Providerdb ']
ITEM[0] is the value of the first list of loops [' Alice ', ' Bob ']. ITEM[1] is the value of the second list. Represents a loop that creates two users for Alice and Bob, and gives them all permissions on three databases.
You can also assign a user list to a variable beforehand:
Tasks
-Name:here, ' users ' contains the above list of employees
mysql_user:name={{item[0]}} priv={{item[1]}}.*:all append_privs=yes Password=foo
With_nested:
-"{{users}}"
-[' Clientdb ', ' employeedb ', ' Providerdb ']
3, With_dict
With_dict can traverse more complex data structures:
If you have the following variable contents:
Users
Alice
Name:alice Appleworth
telephone:123-456-7890
Bob
Name:bob Bananarama
telephone:987-654-3210
Now you need to output the user name and phone number for each user:
Tasks
-Name:print phone records
Debug:msg= "User {{Item.key}} is {{item.value.name}}} ({{item.value.telephone}})"
With_dict: "{{users}}"
4. with_fileglob File Matching traversal
You can specify a directory that uses With_fileglob to iterate through all the files in this directory, as shown in the following example:
Tasks
With_fileglob:
Assemble:src=/root/.sshkeys dest=/root/.ssh/authorized_keysmode=0600 owner=root group=root
5. With_subelement traversing child elements
If you need to traverse a list of users now and create each user, you also need to configure each user to log in with a specific SSH key. The contents of the variable file are as follows:
Users
-Name:alice
Authorized
-/tmp/alice/onekey.pub
-/tmp/alice/twokey.pub
Mysql:
Password:mysql-password
Hosts
- "%"
-"127.0.0.1"
-":: 1"
-"localhost"
Privs:
-"*.*:select"
-"Db1.*:all"
-Name:bob
Authorized
-/tmp/bob/id_rsa.pub
Mysql:
Password:other-mysql-password
Hosts
-"DB1"
Privs:
-"*.*:select"
-"Db2.*:all"
playbook中定义如下:
- user: name={{ item.name }} state=present generate_ssh_key=yes
with_items: "{{users}}"
- authorized_key: "user={{ item.0.name }} key=‘{{ lookup(‘file‘, item.1) }}‘"
with_subelements:
- users
- authorized
也可以遍历嵌套的子列表:
- name: Setup MySQL users
mysql_user: name={{ item.0.name }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join(‘/‘) }}
with_subelements:
- users
- mysql.hosts
6、with_sequence循环整数序列
With_sequence can generate an auto-increment sequence of integers, you can specify the starting and ending values, or you can specify the growth step. The parameter is specified as Key=value, and format specifies the form of the output. The number can be decimal, 16 binary, octal:
-Hosts:all
Tasks
# Create Groups
-Group:name=evens State=present
-Group:name=odds State=present
# Create some test users
-user:name={{Item}} state=present Groups=evens
With_sequence:start=0 end=32 format=testuser%02d
# Create a series of directories with even numbers for some reason
-file:dest=/var/stuff/{{Item}} state=directory
with_sequence:start=4 end=16 stride=2 # Stride for specifying stride length
# a simpler the sequence plugin
# Create 4 groups
-group:name=group{{Item}} state=present
With_sequence:count=4
7、with_random_choice随机选择
Randomly take a value from the list:
-debug:msg={{Item}}
With_random_choice:
-"Go through the door"
-"Drink from the Goblet"
-"Press the red button"
-"Do Nothing"
8. Do-util Cycle
Example:
-Action:shell/usr/bin/foo
Register:result
Until:result.stdout.find ("All Systems go")! =-1
Retries:5
Delay:10
Executes the shell module repeatedly, stopping when the shell module executes the command output that contains "all systems Go". Retry 5 times, delay time 10 seconds. Retries Default value is 3,delay default is 5. The return value of the task is the return result of the last loop.
9. Cyclic Registration variables
When using register in a loop, the saved result contains the results keyword, which saves a list of the results of the module execution
-Shell:echo "{{Item}}"
With_items:
-One
-Double
Register:echo
The variable echo content is as follows:
{
"Changed": true,
"MSG": "All items Completed",
"Results": [
{
"Changed": true,
"cmd": "Echo \" One\ "",
"Delta": "0:00:00.003110",
"End": "2013-12-19 12:00:05.187153",
"Invocation": {
"Module_args": "Echo \" One\ "",
"Module_name": "Shell"
},
"Item": "One",
"RC": 0,
"Start": "2013-12-19 12:00:05.184043",
"StdErr": "",
"stdout": "One"
},
{
"Changed": true,
"cmd": "Echo \" Two\ "",
"Delta": "0:00:00.002920",
"End": "2013-12-19 12:00:05.245502",
"Invocation": {
"Module_args": "Echo \" Two\ "",
"Module_name": "Shell"
},
"Item": "Both",
"RC": 0,
"Start": "2013-12-19 12:00:05.242582",
"StdErr": "",
"stdout": "The Other"
}
]
}
The result of traversing a registered variable:
-Name:fail If return code is not 0
Fail
msg: "The command ({{item.cmd}}) did not have a 0 return code"
When:item.rc! = 0
With_items: "{{echo.results}}"
10. With_together Traversal Data Parallel collection
Example:
-Hosts:webservers
Remote_user:root
VARs
Alpha: [' A ', ' B ', ' C ', ' d ']
Numbers: [1,2,3,4]
Tasks
-debug:msg= "{{item.0}} and {{item.1}}"
With_together:
-"{{alpha}}"
-"{{numbers}}"
The result of the output is:
OK: [192.168.1.65] = (item=[' A ', 1]) + = {
"Item": [
"A",
1
],
"MSG": "A and 1"
}
OK: [192.168.1.65] = (item=[' B ', 2]) + = {
"Item": [
"B",
2
],
"MSG": "B and 2"
}
OK: [192.168.1.65] = (item=[' C ', 3]) + = {
"Item": [
"C",
3
],
"MSG": "C and 3"
}
OK: [192.168.1.65] = (item=[' d ', 4]) + = {
"Item": [
"D",
4
],
"MSG": "D and 4"
}
Loop modules are typically used in the following scenarios
A similar configuration module is repeated multiple times
Fact is a list
Create multiple files and then use assemble to synthesize a large file
Using With_fileglob to match specific file management
This article is from the "Nobody" blog, please be sure to keep this source http://breezey.blog.51cto.com/2400275/1757636
Ansible8:playbook cycle "Turn"