欢迎来到战五渣的博客

人生三重境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。

010.Ansible_palybook 循环语句

Ansible循环语句

1 简介

我们在编写playbook的时候,不可避免的要执行一些重复性操作,比如指安装软件包,批量创建用户,操作某个目录下的所有文件等。正如我们所说,ansible一门简单的自动化语言,所以流程控制、循环语句这些编程语言的基本元素它同样都具备。

在Ansible 2.5以前,playbook通过不同的循环语句以实现不同的循环,这些语句使用with_作为前缀。这些语法目前仍然兼容,但在未来的某个时间点,会逐步废弃。

2 with_items

[root@node1 ansible]# vim with_items.yml

- hosts: demo2.example.com
  gather_facts: no 
  tasks:
    - debug:
        msg: "{{ item }}"
      with_items: "{{ groups.webserver }}"

相当于

- hosts: demo2.example.com
  gather_facts: no 
  tasks:
    - debug:
        msg: "{{ item }}"
      with_items:
        - demo1.example.com
        - demo2.example.com
        - demo3.example.com

[root@node1 ansible]# ansible-playbook with_items.yml

ok: [demo2.example.com] => (item=demo1.example.com) => {
    "msg": "demo1.example.com"
}
ok: [demo2.example.com] => (item=demo2.example.com) => {
    "msg": "demo2.example.com"
}
ok: [demo2.example.com] => (item=demo3.example.com) => {
    "msg": "demo3.example.com"
}

[root@node1 ansible]# vim with_items.yml

- hosts: demo2.example.com
  gather_facts: no 
  tasks:
    - name: "create directory"
      file: 
        path: "/tmp/{{ item.path1 }}/{{ item.path2 }}"
        state: directory
      with_items:
        - {path1: a, path2: b} 
        - {path1: c, path2: d}

执行

[root@node1 ansible]# ansible demo2.example.com  -m shell -a "ls -l /tmp/{a,c}"

/tmp/a:
total 0
drwxr-xr-x 2 root root 6 May  2 01:01 b

/tmp/c:
total 0
drwxr-xr-x 2 root root 6 May  2 01:01 d

with_list与 with_items一样,也是用于循环列表。区别是,如果列表的值也是列表,with_iems会将第一层嵌套的列表拉平,而with_list会将值作为一个整体返回。with_flatten会将所有列表全部拉平

[[1,2,[3,4]],[5,6],7,8]   

with_item------->[1,2,[3,4],5,6,7,8]    拉平第一层

with_list--------->[[1,2,[3,4]],[5,6],7,8]   整体返回

with_flatten----->[1,2,3,4,5,6,7,8]     全部拉平

3 with_togther

将两个列表对齐合并

[root@node1 ansible]# vim with_items.yml 

- hosts: demo2.example.com
  gather_facts: no 
  vars:
    alpha: [ 'a','b','c','d']
    numbers: [ 1,2,3,4 ]
  tasks:
    - debug: msg="{{ item.0 }} and {{ item.1 }}"
      with_together:
         - "{{ alpha }}"
         - "{{ numbers }}"

[root@node1 ansible]# ansible-playbook with_items.yml

ok: [demo2.example.com] => (item=[u'a', 1]) => {
    "msg": "a and 1"
}
ok: [demo2.example.com] => (item=[u'b', 2]) => {
    "msg": "b and 2"
}
ok: [demo2.example.com] => (item=[u'c', 3]) => {
    "msg": "c and 3"
}
ok: [demo2.example.com] => (item=[u'd', 4]) => {
    "msg": "d and 4"
}

4 with_nested

嵌套循环,相当于像个for

[root@node1 ansible]# vim with_items.yml

- hosts: demo2.example.com
  gather_facts: no 
  tasks:
    - debug: msg="name is {{ item[0] }}  vaule is {{ item[1] }} num is {{ item[2] }}"
      with_nested:
        - ['alice','bob']
        - ['a','b','c']
        - ['1','2','3']

item[0]是循环的第一个列表的值["alice","bob"] item[1]是第二个列表的值;以上的执行输出如下:

[root@node1 ansible]# ansible-playbook with_items.yml

ok: [demo2.example.com] => (item=[u'alice', u'a', u'1']) => {
    "msg": "name is alice  vaule is a num is 1"
}
ok: [demo2.example.com] => (item=[u'alice', u'a', u'2']) => {
    "msg": "name is alice  vaule is a num is 2"
}
ok: [demo2.example.com] => (item=[u'alice', u'a', u'3']) => {
    "msg": "name is alice  vaule is a num is 3"
}
ok: [demo2.example.com] => (item=[u'alice', u'b', u'1']) => {
    "msg": "name is alice  vaule is b num is 1"
}
ok: [demo2.example.com] => (item=[u'alice', u'b', u'2']) => {
    "msg": "name is alice  vaule is b num is 2"
}
ok: [demo2.example.com] => (item=[u'alice', u'b', u'3']) => {
    "msg": "name is alice  vaule is b num is 3"
}
ok: [demo2.example.com] => (item=[u'alice', u'c', u'1']) => {
    "msg": "name is alice  vaule is c num is 1"
}
ok: [demo2.example.com] => (item=[u'alice', u'c', u'2']) => {
    "msg": "name is alice  vaule is c num is 2"
}
ok: [demo2.example.com] => (item=[u'alice', u'c', u'3']) => {
    "msg": "name is alice  vaule is c num is 3"
}
ok: [demo2.example.com] => (item=[u'bob', u'a', u'1']) => {
    "msg": "name is bob  vaule is a num is 1"
}
ok: [demo2.example.com] => (item=[u'bob', u'a', u'2']) => {
    "msg": "name is bob  vaule is a num is 2"
}
ok: [demo2.example.com] => (item=[u'bob', u'a', u'3']) => {
    "msg": "name is bob  vaule is a num is 3"
}
ok: [demo2.example.com] => (item=[u'bob', u'b', u'1']) => {
    "msg": "name is bob  vaule is b num is 1"
}
ok: [demo2.example.com] => (item=[u'bob', u'b', u'2']) => {
    "msg": "name is bob  vaule is b num is 2"
}
ok: [demo2.example.com] => (item=[u'bob', u'b', u'3']) => {
    "msg": "name is bob  vaule is b num is 3"
}
ok: [demo2.example.com] => (item=[u'bob', u'c', u'1']) => {
    "msg": "name is bob  vaule is c num is 1"
}
ok: [demo2.example.com] => (item=[u'bob', u'c', u'2']) => {
    "msg": "name is bob  vaule is c num is 2"
}
ok: [demo2.example.com] => (item=[u'bob', u'c', u'3']) => {
    "msg": "name is bob  vaule is c num is 3"
}

with_cartesian功能完全一样

5 with_index_items

在循环处理列表时,为列表的每一项添加索引

[root@node1 ansible]# vim with_items.yml

- hosts: demo2.example.com
  gather_facts: no 
  tasks:
    - debug: 
        msg: "{{ item }}"
      with_indexed_items:
        - test1
        - test2
        - test3

[root@node1 ansible]# ansible-playbook with_items.yml

ok: [demo2.example.com] => (item=[0, u'test1']) => {
    "msg": [
        0, 
        "test1"
    ]
}
ok: [demo2.example.com] => (item=[1, u'test2']) => {
    "msg": [
        1, 
        "test2"
    ]
}
ok: [demo2.example.com] => (item=[2, u'test3']) => {
    "msg": [
        2, 
        "test3"
    ]
}

6 with_sequence

用于返回一个数字序列

参数说明

start:指走起始值

end:指定结束值

stride:指定步长,即从 start至end,每次增加的值

count:生成连续的数字序列,从1开始,到 count的值结束

format:格式化输出类似于lnuX命令行中的 printi格式化输出

- 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用于指定步长
    # a simpler way to use the sequence plugin
    # create 4 groups
    - group: name=group{{ item }} state=present
      with_sequence: count=4

7 with_random_choice

- debug: msg={{ item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

8 with_dict

[root@node1 ansible]# vi with_items.yml

- hosts: demo2.example.com
  gather_facts: no 
  vars: 
    users:
      alice:
        name: Alice Appleworth
        telephone: 123-456-7890
      bob:
        name: Bob Bananarama
        telephone: 987-654-3210

# 现在需要输出每个用户的用户名和手机号:
  tasks:
    - name: Print phone records
      debug: 
        msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
      with_dict: "{{ users }}"

[root@node1 ansible]# ansible-playbook with_items.yml

ok: [demo2.example.com] => (item={'value': {u'name': u'Bob Bananarama', u'telephone': u'987-654-3210'}, 'key': u'bob'}) => {
    "msg": "User bob is Bob Bananarama (987-654-3210)"
}
ok: [demo2.example.com] => (item={'value': {u'name': u'Alice Appleworth', u'telephone': u'123-456-7890'}, 'key': u'alice'}) => {
    "msg": "User alice is Alice Appleworth (123-456-7890)"
}

9 with_subelement

假如现在需要遍历一个用户列表,并创建每个用户,而且还需要为每个用户配置以特定的SSH key登录。变量文件内容如下:

with_file,是在主控端完成

上面with_file用于获取文的内容,而 with_fileglob则用于匹配文件名称。可以通过该关键字,在指定的目录中匹配符合模式的文件名。与 with_file相同的是,with_ fileglob操作的文件也是主控端的文件而非被控端的文件

10 loop关键字说明

在playbook中使用循环,直接使用loop关键字即可。

with_list,with_item可以直接试用loop代替

with_flatten,loop:"{{  testlist| flatten}}"

启动httpd和postfilx服务:

tasks:
  - name: postfix and httpd are running
    service:
      name: "{{ item }}"
      state: started
    loop:
      - postfix
      - httpd

也可以将loop循环的列表提前赋值给一个变量,然后在循环语句中调用:

#cat test_services.yml
test_services:
  - postfix
  - httpd

# cat install_pkgs.yml 
- name: start services
  hosts: test
  vars_files:
    - test_services.yml
  tasks:
    - name: postfix and httpd are running
      service:
        name: "{{ item }}"
        state: started
      loop: "{{ test_services }}"

下面是一个循环更复杂类型数据的示例:

# cat test_loop.yml 
- name: test loop
  hosts: test
  tasks:
  - name: add www group
    group: 
      name: www
  - name: add several users
    user: 
      name: "{{ item.name }}"
      state: present 
      groups: "{{ item.groups }}"
    loop:
      - { name: 'testuser1', groups: 'wheel' }
      - { name: 'testuser2', groups: 'www' }

11 在循环语句中注册变量

下面是一个register的变量在循环中使用的例子:

# cat register_loop.yml 
- name: registered variable usage as a loop list
  hosts: test
  tasks:
      - name: ensure /mnt/bkspool exists
        file:
          path: /mnt/bkspool
          state: directory
      - name: retrieve the list of home directories
        command: ls /home
        register: home_dirs
      - name: Show home_dirs results
        debug:
          var: home_dirs.stdout_lines
      - name: add home dirs to the backup spooler
        file: 
          path: /mnt/bkspool/{{ item }}
          src: /home/{{ item }}
          state: link
          force: yes
        loop: "{{ home_dirs.stdout_lines }}"

在循环语句中注册变量:

- name: Loop Register test
  gather_facts: no
  hosts: webserver
  tasks:
    - name: Looping Echo Task
      shell: "echo this is my item: {{ item }}"
      loop:
        - one
        - two
      register: echo_results
    - name: Show echo_results variable
      debug:
        var: echo_results

执行语句,可以看到变量的

 "echo_results": {
        "changed": true, 
        "msg": "All items completed", 
        "results": [
            {
                "ansible_loop_var": "item", 
                "changed": true, 
                "cmd": "echo this is my item: one", 
                "delta": "0:00:00.004610", 
                "end": "2020-05-02 02:16:40.824482", 
                "failed": false, 
                "invocation": {
                    "module_args": {
                        "_raw_params": "echo this is my item: one", 
                        "_uses_shell": true, 
                        "argv": null, 
                        "chdir": null, 
                        "creates": null, 
                        "executable": null, 
                        "removes": null, 
                        "stdin": null, 
                        "stdin_add_newline": true, 
                        "strip_empty_ends": true, 
                        "warn": true
                    }
                }, 
                "item": "one", 
                "rc": 0, 
                "start": "2020-05-02 02:16:40.819872", 
                "stderr": "", 
                "stderr_lines": [], 
                "stdout": "this is my item: one", 
                "stdout_lines": [
                    "this is my item: one"
                ]
            }, 
            {
                "ansible_loop_var": "item", 
                "changed": true, 
                "cmd": "echo this is my item: two", 
                "delta": "0:00:00.006417", 
                "end": "2020-05-02 02:16:41.372681", 
                "failed": false, 
                "invocation": {
                    "module_args": {
                        "_raw_params": "echo this is my item: two", 
                        "_uses_shell": true, 
                        "argv": null, 
                        "chdir": null, 
                        "creates": null, 
                        "executable": null, 
                        "removes": null, 
                        "stdin": null, 
                        "stdin_add_newline": true, 
                        "strip_empty_ends": true, 
                        "warn": true
                    }
                }, 
                "item": "two", 
                "rc": 0, 
                "start": "2020-05-02 02:16:41.366264", 
                "stderr": "", 
                "stderr_lines": [], 
                "stdout": "this is my item: two", 
                "stdout_lines": [
                    "this is my item: two"
                ]
            }
        ]
    }
}

返回结果为一个字典列表


博主声明:本文的内容来源主要来自誉天教育晏威老师,由本人实验完成操作验证,需要的博友请联系誉天教育(http://www.yutianedu.com/),获得官方同意或者晏老师(https://www.cnblogs.com/breezey/)本人同意即可转载,谢谢!

posted @ 2020-05-02 10:37  梦中泪  阅读(413)  评论(0编辑  收藏  举报