设为首页 收藏本站
查看: 2045|回复: 0

[经验分享] 自动化运维工具Ansible之Playbooks循环语句

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-8-6 10:00:12 | 显示全部楼层 |阅读模式
在使用ansible做自动化运维的时候,免不了的要重复执行某些操作,如:添加几个用户,创建几个MySQL用户并为之赋予权限,操作某个目录下所有文件等等。好在playbooks支持循环语句,可以使得某些需求很容易而且很规范的实现。
with_items是playbooks中最基本也是最常用的循环语句。

1
2
3
4
5
- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - testuser1
     - testuser2



上边例子表示,添加两个用户分别为testuser1,testuser2。
也可以将用户列表提前赋值给一个变量,然后在循环语句中调用:
1
with_items: "{{ somelist }}"



使用with_items迭代循环的变量可以是个单纯的列表,也可以是一个可以迭代的较为复杂的数据结构,如字典类型:
1
2
3
4
5
- name: add several users
  user: name={{ item.name }} state=present groups={{ item.groups }}
  with_items:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }




嵌套循环


1
2
3
4
5
- 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]是循环的第一个列表的值['alice','bob']。item[1]是第二个列表的值。表示循环创建alice和bob两个用户,并且为其赋予在三个数据库上的所有权限。

也可以将用户列表事先赋值给一个变量:
1
2
3
4
5
- 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' ]




with_dict可以遍历更复杂的数据结构:
如,有以下变量内容:

1
2
3
4
5
6
7
8
---
users:
  alice:
    name: Alice Appleworth
    telephone: 123-456-7890
  bob:
    name: Bob Bananarama
    telephone: 987-654-3210



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




文件匹配遍历
with_fileglob匹配单个目录下所有文件

1
2
3
4
5
6
7
8
9
10
11
12
---
- hosts: all

  tasks:

    # first ensure our target directory exists
    - file: dest=/etc/fooapp state=directory

    # copy each file over that matches the given pattern
    - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
      with_fileglob:
        - /playbooks/files/fooapp/*



注:在角色中以相对路径使用with_fileglob,ansible会将路径解析为role/<rolename>/files。

遍历数据并行集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
[iyunv@web1 ~]# cat /etc/ansible/loop.yml
---
- 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 }}"

[iyunv@web1 ~]# ansible-playbook /etc/ansible/loop.yml

PLAY [webservers] *************************************************************

GATHERING FACTS ***************************************************************
ok: [192.168.1.65]

TASK: [debug msg="{{ item.0 }} and {{ item.1 }}"] *****************************
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"
}

PLAY RECAP ********************************************************************
192.168.1.65               : ok=2    changed=0    unreachable=0    failed=0



遍历子元素
假如现在需要遍历一个用户列表,并创建每个用户,而且还需要为每个用户配置以特定的SSH key登录。变量文件内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
---
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"



playbooks中定义如下:
1
2
3
4
5
6
7
- 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



也可以遍历嵌套的子列表:
1
2
3
4
5
- name: Setup MySQL users
  mysql_user: name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}
  with_subelements:
    - users
    - mysql.hosts



循环整数序列
with_sequence可以生成一个自增的整数序列,可以指定起始值和结束值,也可以指定增长步长。
参数以key=value的形式指定,format指定输出的格式。
数字可以是十进制,十六进制,八进制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
---
- 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%02x

    # 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

    # a simpler way to use the sequence plugin
    # create 4 groups
    - group: name=group{{ item }} state=present
      with_sequence: count=4



随机选择
with_random_choice可以从列表中随机取一个值。

1
2
3
4
5
6
- debug: msg={{ item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"



Do-Until 循环
1
2
3
4
5
- action: shell /usr/bin/foo
  register: result
  until: result.stdout.find("all systems go") != -1
  retries: 5
  delay: 10



上边的例子重复执行shell模块,当shell模块执行的命令输出内容中包含"all systems go"的时候停止执行。重试5次,延迟时间10秒。retries默认值为3,delay默认值为5。
任务的返回值为最后一次循环的返回结果。

循环注册变量
在循环中使用register时,索保存的结果中包含results关键字,该关键字保存模块执行结果的列表
1
2
3
4
5
- shell: echo "{{ item }}"
  with_items:
    - one
    - two
  register: echo



变量echo内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
{
    "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": "two",
            "rc": 0,
            "start": "2013-12-19 12:00:05.242582",
            "stderr": "",
            "stdout": "two"
        }
    ]
}



遍历注册变量的结果:
1
2
3
4
5
- 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}}"



示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
[iyunv@web1 ~]# cat /etc/ansible/reloop.yml
---
- hosts: webservers
  remote_user: root
  tasks:
   - shell: echo "{{ item }}"
     with_items:
      - one
      - two
     register: echo
   - debug: msg="{{ echo }}"
   - name: Fail if return code is not 0
     fail: msg=" The command {{ item.cmd }} has a 0 return code"
     when: item.rc != 0
     with_items: "{{ echo.results }}"


[iyunv@web1 ~]# ansible-playbook /etc/ansible/reloop.yml

PLAY [webservers] *************************************************************

GATHERING FACTS ***************************************************************
ok: [192.168.1.65]

TASK: [shell echo "{{ item }}"] ***********************************************
changed: [192.168.1.65] => (item=one)
changed: [192.168.1.65] => (item=two)

TASK: [debug msg="{{ echo }}"] ************************************************
ok: [192.168.1.65] => {
    "msg": "{'msg': 'All items completed', 'changed': True, 'results': [{u'stdout': u'one', u'changed': True, u'end': u'2015-08-05 11:30:42.560652', u'start': u'2015-08-05 11:30:42.549056', u'cmd': u'echo \"one\"', u'rc': 0, 'item': 'one', u'stderr': u'', u'delta': u'0:00:00.011596', 'invocation': {'module_name': u'shell', 'module_args': u'echo \"one\"'}, 'stdout_lines': [u'one'], u'warnings': []}, {u'stdout': u'two', u'changed': True, u'end': u'2015-08-05 11:30:44.105387', u'start': u'2015-08-05 11:30:44.093500', u'cmd': u'echo \"two\"', u'rc': 0, 'item': 'two', u'stderr': u'', u'delta': u'0:00:00.011887', 'invocation': {'module_name': u'shell', 'module_args': u'echo \"two\"'}, 'stdout_lines': [u'two'], u'warnings': []}]}"
}

TASK: [Fail if return code is not 0] ******************************************
skipping: [192.168.1.65] => (item={u'cmd': u'echo "one"', u'end': u'2015-08-05 11:30:42.560652', u'stderr': u'', u'stdout': u'one', u'changed': True, u'rc': 0, 'item': 'one', u'warnings': [], u'delta': u'0:00:00.011596', 'invocation': {'module_name': u'shell', 'module_args': u'echo "one"'}, 'stdout_lines': [u'one'], u'start': u'2015-08-05 11:30:42.549056'})
skipping: [192.168.1.65] => (item={u'cmd': u'echo "two"', u'end': u'2015-08-05 11:30:44.105387', u'stderr': u'', u'stdout': u'two', u'changed': True, u'rc': 0, 'item': 'two', u'warnings': [], u'delta': u'0:00:00.011887', 'invocation': {'module_name': u'shell', 'module_args': u'echo "two"'}, 'stdout_lines': [u'two'], u'start': u'2015-08-05 11:30:44.093500'})

PLAY RECAP ********************************************************************
192.168.1.65               : ok=4    changed=1    unreachable=0    failed=0



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-94641-1-1.html 上篇帖子: 自动化运维工具Ansible之Playbooks的roles和include 下篇帖子: 自动化运维工具Ansible之Playbooks的when语句
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表