1. 程式人生 > >自動化運維工具Ansible實戰(七)playbook循環

自動化運維工具Ansible實戰(七)playbook循環

ansible ansible-play

(一)簡述

在使用ansible做自動化運維的時候,免不了的要重復執行某些操作,如:添加幾個用戶,創建幾個MySQL用戶並為之賦予權限,操作某個目錄下所有文件等等。好在playbook支持循環語句,可以使得某些需求很容易而且很規範的實現。


(二)常用的循環語句

1,with_items。with_items是playbooks中最基本也是最常用的循環語句:

語法:

tasks:
- name:Secure config files
    file: path=/etc/{{ item }} mode=0600 owner=root group=root
    with_items:
        - my.cnf
        - shadow
        - fstab
    或with_items:"{{ somelist }}"
###上面的例子說明在/etc下創建權限級別為600,屬主屬組都是root三個文件
使用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嵌套循環

示例:

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]是循環的第一個列表的值[‘alice‘,‘bob‘]。item[1]是第二個列表的值。表示循環創建alice和bob兩個用戶,並且為其賦予在三個數據庫上的所有權限。

也可以將用戶列表事先賦值給一個變量:

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可以遍歷更復雜的數據結構。假如有如下變量內容:

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


4、with_fileglob文件匹配遍歷

####可以指定一個目錄,使用with_fileglob可以循環這個目錄中的所有文件,示例如下:
tasks:
- name:Make key directory     
      file: path=/root/.sshkeys ensure=directory mode=0700 owner=root group=root     
- name:Upload public keys     
      copy: src={{ item }} dest=/root/.sshkeys mode=0600 owner=root group=root     
      with_fileglob:
        - keys/*.pub     
- name:Assemble keys into authorized_keys file     
      assemble: src=/root/.sshkeys dest=/root/.ssh/authorized_keysmode=0600 owner=root group=root

5、with_subelement遍歷子元素

假如現在需要遍歷一個用戶列表,並創建每個用戶,而且還需要為每個用戶配置以特定的SSH key登錄。變量文件內容如下:

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可以生成一個自增的整數序列,可以指定起始值和結束值,也可以指定增長步長。 參數以key=value的形式指定,format指定輸出的格式。數字可以是十進制、十六進制、八進制:

- 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、do-Util循環

示例:

- 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。任務的返回值為最後一次循環的返回結果。


9、循環註冊變量

在循環中使用register時,保存的結果中包含results關鍵字,該關鍵字保存模塊執行結果的列表

- shell: echo "{{ item }}"
  with_items:
    - one
    - two
  register: echo
變量echo內容如下:
{
    "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"
        }
    ]
}
##遍歷註冊變量的結果:
- 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遍歷數據並行集合

示例:
- 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 }}"
輸出的結果為:
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模塊一般在下面的場景中使用

  1. 類似的配置模塊重復了多遍

  2. fact是一個列表

  3. 創建多個文件,然後使用assemble聚合成一個大文件

  4. 使用with_fileglob匹配特定的文件管理


本文出自 “清風明月” 博客,請務必保留此出處http://liqingbiao.blog.51cto.com/3044896/1969595

自動化運維工具Ansible實戰(七)playbook循環