访次: AmazingCounters.com 次

ansible_playbook语法中的循环语句归纳

ansible_playbook语法中的循环语句归纳

种类一、标准循环
添加多个用户

- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - test1
     - test2
添加多个用户,并将用户加入不同的组内
- name: add several users
  user: name={{ item.name }} state=present groups={{ item.groups }}
  with_items:
    - { name: 'test1', groups: 'wheel' }
    - { name: 'test2', groups: 'root' }

种类二、锚点嵌套循环

嵌套循环主要实现一对多,多对多的合并。

复制代码
- hosts: abc
  gather_facts: False
  tasks:
  - name: debug loops
    debug: msg="name is {{ item[0] }} vaule is {{ item[1] }} num is {{ item[2] }} num is {{ item[3] }}"
    with_nested:
      - ['悟空','猪八戒','唐僧']
      - ['a','b','c']
      - ['1','2','3']
      - ['w1','w2','w3']
  tags:
    loops
复制代码

可以将代码复制至xxx.yaml 文件中

通过:ansible-playbook loops.yaml --syntax-check 检查语法

通过:ansible-playbook loops.yaml --list-tasks 查看标签

通过:ansible-playbook loops.yaml --tags=loops 来执行对应标签的任务,这里定义了loops任务,仔细观察执行后的结果就会发现嵌套循环的规律也就很容易理解嵌套循环了

 种类三、锚点遍历字典
输出用户的姓名和电话

复制代码
- hosts: abc
  gather_facts: False
  tasks:
    - name: Print phone records
  #item.key 相当于 aliceitem.value.name 相当于 Alice Appleworthitem.value.telephone 相当于123-456-789
#此方法为Python字典方式key:value 方式调用
debug
: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})" with_dict: {'alice':{'name':'Alice Appleworth', 'telephone':'123-456-789'},'bob':{'name':'Bob Bananarama', 'telephone':'987-654-3210'} } tags: print #"msg": "User alice is Alice Appleworth (123-456-789)"
复制代码

 

 

 种类四、锚点并行遍历列表

  tasks:
    - debug: "msg={{ item.0 }} and {{ item.1 }}"
      with_together:
      - [ 'a', 'b', 'c', 'd','e' ]
      - [ 1, 2, 3, 4 ]
  tags:
    pwd

 如果列表数目不匹配则用Null 补全

种类五、锚点遍历列表和索引

- hosts: abc
  gather_facts: False
  tasks:
    - name: indexed loop demo
      debug: "msg='at array position {{ item.0 }} there is a value {{ item.1 }}'"
      with_indexed_items: [a,b,c,d,e,f,g]
  tags:
    indexed

输出结果:

复制代码
[root@node2 ansible-playbooks]# ansible-playbook indexed.yaml --tags=indexed

PLAY [abc] **********************************************************************************************************************************************************************************************************************************

TASK [indexed loop demo] ********************************************************************************************************************************************************************************************************************
ok: [127.0.0.1] => (item=(0, u'a')) => {
    "changed": false, 
    "item": [
        0, 
        "a"
    ], 
    "msg": "at array position 0 there is a value a"
}
ok: [127.0.0.1] => (item=(1, u'b')) => {
    "changed": false, 
    "item": [
        1, 
        "b"
    ], 
    "msg": "at array position 1 there is a value b"
}
ok: [127.0.0.1] => (item=(2, u'c')) => {
    "changed": false, 
    "item": [
        2, 
        "c"
    ], 
    "msg": "at array position 2 there is a value c"
}
ok: [127.0.0.1] => (item=(3, u'd')) => {
    "changed": false, 
    "item": [
        3, 
        "d"
    ], 
    "msg": "at array position 3 there is a value d"
}
ok: [127.0.0.1] => (item=(4, u'e')) => {
    "changed": false, 
    "item": [
        4, 
        "e"
    ], 
    "msg": "at array position 4 there is a value e"
}
ok: [127.0.0.1] => (item=(5, u'f')) => {
    "changed": false, 
    "item": [
        5, 
        "f"
    ], 
    "msg": "at array position 5 there is a value f"
}
ok: [127.0.0.1] => (item=(6, u'g')) => {
    "changed": false, 
    "item": [
        6, 
        "g"
    ], 
    "msg": "at array position 6 there is a value g"
}

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=0  
输出结果:ansible-playbook indexed.yaml --tags=indexed
复制代码

item.0 为索引,item.1为值

种类六、锚点比哪里文件列表内容

复制代码
- hosts: abc
  gather_facts: False
  tasks:
    - debug:
        msg: "{{ item }}"
      with_file:
        - /home/loops.log
        - /home/newloops.log
      tags:
        pwd
复制代码
复制代码
[root@node2 ansible-playbooks]# ansible-playbook test6.yaml --tags=pwd

PLAY [abc] ***********************************************************************************************

TASK [debug] *********************************************************************************************
ok: [127.0.0.1] => (item=hello) => {
    "changed": false, 
    "item": "hello", 
    "msg": "hello"
}
ok: [127.0.0.1] => (item=world) => {
    "changed": false, 
    "item": "world", 
    "msg": "world"
}

PLAY RECAP ***********************************************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=0 
输出结果:ansible-playbook test6.yaml --tags=pwd
复制代码

种类七、锚点遍历目录文件

with_fileglob 匹配单个目录中的所有文件,非递归模式匹配

复制代码
- hosts: abc
  gather_facts: False
  tasks:
    - file: dest=/home/loops.log state=directory
    - copy: src={{ item }} dest=/tmp/ owner=root mode=600
      with_fileglob:
        - /home/*.log
      tags:
        pwd
    #- debug: 
    #    msg: "{{ item }}"
    #  with_fileglob:
    #    - /home/*.log
    #    #- /home/newloops.log
    #  tags:
    #    pwd
复制代码

 

复制代码
[root@node2 ansible-playbooks]# ansible-playbook test7.yaml --list-tasks

playbook: test7.yaml

  play #1 (abc): abc    TAGS: []
    tasks:
      file      TAGS: []
      copy      TAGS: [pwd]
[root@node2 ansible-playbooks]# ansible-playbook test7.yaml --tags=pwd

PLAY [abc] ***********************************************************************************************

TASK [copy] **********************************************************************************************
changed: [127.0.0.1] => (item=/home/loops.log)
changed: [127.0.0.1] => (item=/home/newloops.log)

PLAY RECAP ***********************************************************************************************
127.0.0.1                  : ok=1    changed=1    unreachable=0    failed=0 
输出结果:ansible-playbook test7.yaml --list-tasks
复制代码
[root@node2 ansible-playbooks]# ll /tmp/loops.log 
-rw------- 1 root root 6 Mar 26 12:24 /tmp/loops.log
[root@node2 ansible-playbooks]# ll /tmp/newloops.log 
-rw------- 1 root root 6 Mar 26 12:24 /tmp/newloops.log
当在role中使用with_fileglob的相对路径时,Ansible解析相对于roles/<rolename>/files目录的路径

 种类八、锚点遍历ini 文件

lookup.ini
[section1]
value1=section1/value1
value2=section1/value2

[section2]
value1=section2/value1
value2=section2/value2

- debug: msg="{{ item }}"
  with_ini: value[1-2] section=section1 file=lookup.ini re=true

获取section1 里的value1和value2的值

 种类九、锚点重试循环 until

复制代码
- hosts: abc
  gather_facts: False

  tasks:
    - action: shell /usr/bin/foo
      register: result
      until: result.stdout.find("all systems go") != -1
      retries: 5
      delay:  10
  tags:
    until
复制代码

"重试次数retries" 的默认值为3,"delay"为5。

锚点查找第一个匹配文件

tasks:
  - debug: "msg={{ item }}"
    with_first_found:
     - "/tmp/a"
     - "/tmp/b"
     - "/tmp/default.conf"

依次寻找列表中的文件,找到就返回。如果列表中的文件都找不到,任务会报错。

种类十、锚点随机选择with_random_choice

随机选择列表中的一个值

复制代码
- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_random_choice:
        - "go through the door"
        - "drink from the goblet"
        - "press the red button"
        - "do nothing"
  tags:
    random
复制代码

检查语法

[root@node2 ansible-playbooks]# ansible-playbook with_random_choice.yaml --syntax-check

playbook: with_random_choice.yaml

查看任务标签

[root@node2 ansible-playbooks]# ansible-playbook with_random_choice.yaml --list-tasks

playbook: with_random_choice.yaml

  play #1 (abc): abc    TAGS: [random]
    tasks:
      debug     TAGS: [random]
[root@node2 ansible-playbooks]# 

执行任务:

循环程序的结果:

- hosts: abc
  gather_facts: False
  tasks:
    - debug: "msg={{ item }}"
      with_lines: ps aux
  tags:
    with-lines

种类十一、锚点循环子元素

定义好变量

复制代码
#varfile
---
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"
复制代码
复制代码
---
- hosts: web
  vars_files: varfile
  tasks:

  - 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
复制代码

{{ lookup('file', item.1) }} 是查看item.1文件的内容

with_subelements 遍历哈希列表,然后遍历列表中的给定(嵌套)的键。

种类十二、锚点在序列中循环with_sequence
with_sequence以递增的数字顺序生成项序列。 您可以指定开始,结束和可选步骤值。 参数应在key = value对中指定。 'format'是一个printf风格字符串。

数字值可以以十进制,十六进制(0x3f8)或八进制(0600)指定。 不支持负数。

 

复制代码
---
- hosts: all

  tasks:

    # 创建组
    - group: name=evens state=present
    - group: name=odds state=present

    # 创建格式为testuser%02x 的0-32 序列的用户
    - user: name={{ item }} state=present groups=evens
      with_sequence: start=0 end=32 format=testuser%02x

    # 创建4-16之间得偶数命名的文件
    - file: dest=/var/stuff/{{ item }} state=directory
      with_sequence: start=4 end=16 stride=2

    # 简单实用序列的方法:创建4 个用户组分表是组group1 group2 group3 group4
    - group: name=group{{ item }} state=present
      with_sequence: count=4
复制代码

合并列表

安装所有列表中的软件

 

复制代码
- hosts: abc
  gather_facts: False
  tasks:
    - name: flattened loop demo
      yum: name={{ item }} state=installed
      with_flattened:
         - [ 'foo-package', 'bar-package' ]
         - [ ['one-package', 'two-package' ]]
         - [ ['red-package'], ['blue-package']]
  tags:
    yum
复制代码

 

注册变量使用循环

复制代码
- hosts: abc
  gather_facts: False
  tasks:
    - shell: echo "{{ item }}"
      with_items:
        - one
        - two
      register: echo

    - 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 }}"
  tags:
    with
复制代码

循环主机清单

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_items: "{{ groups['all'] }}"
  tags:
    all

输出所有执行的主机

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_items: abc
  tags:
    all

输出所有主机清单里的主机

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_inventory_hostnames: all
  tags:
    all

输出主机清单中不在www中的所有主机

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_inventory_hostnames: all:!www
  tags:
    all
复制代码
主机清单内容:
[root@node2 ansible-playbooks]# cat /etc/ansible/hosts
[www]
192.168.92.131
192.168.92.132:30022 testvar="80.183"


[abc]
127.0.0.1 http_port=192.68.92.139:80 access_num=100 server_name="www.xxxx.com"
复制代码

改变循环的变量项

复制代码
# main.yml
- include: inner.yml
  with_items:
    - 1
    - 2
    - 3
  loop_control:
    loop_var: outer_item
# inner.yml
- debug: msg="outer item={{ outer_item }} inner item={{ item }}"
  with_items:
    - a
    - b
    - c
复制代码

 

 

 

https://www.cnblogs.com/hwlong/p/9301008.html

posted @   IT老登  阅读(2449)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
访次: AmazingCounters.com 次
点击右上角即可分享
微信分享提示