Ansible-loop循环语句

1、作用

在写 playbook 的时候发现了很多 task 都要重复引用某个相同的模块,比如一次启动10个服务,或者一次拷贝10个文件,如果按照传统的写法最少要写10次,
这样会显得 playbook 很臃肿。如果使用循环的方式来编写 playbook ,这样可以减少重复编写 task 带来的臃肿;

2、示例1-使用循环批量启动服务

2.1、没有使用loop的playbook

cat << 'CAT_END' > loop-server.yaml
- hosts: httpd
  tasks:
  - name: install httpd mariadb
    yum: name=httpd,mariadb state=latest
  - name: start httpd server
    systemd: name=httpd state=started enabled=yes
  - name: start mariadb server
    systemd: name=mariadb state=started enabled=yes
CAT_END

2.2、使用loop的playbook

cat << 'CAT_END' > loop-server.yaml
- hosts: httpd
  tasks:
  - name: install httpd mariadb
    yum: name=httpd,mariadb state=latest
  - name: start httpd mariadb server
    systemd: name={{item}} state=started enabled=yes
    loop:
      - httpd
      - mariadb
CAT_END

3、示例2-使用循环批量安装软件

cat << 'CAT_END' > loop-server-v2.yaml
- hosts: httpd
  tasks:
  - name: install httpd mariadb
    yum: name={{pack}} state=latest
    vars:
      pack:
        - httpd
        - mariadb
CAT_END

4、示例3-使用循环批量创建用户

cat << 'CAT_END' > loop-user.yaml
- hosts: httpd
  tasks:
  - name: add users
    user:
      name: "{{ item.name }}"
      groups: "{{ item.groups }}"
      state: present
    loop:
      - { name: 'testuser1',groups: 'bin'}
      - { name: 'testuser2',groups: 'root'}
CAT_END

5、示例4-使用循环批量拷贝文件

cat << 'CAT_END' > loop-file.yaml
- hosts: httpd
  tasks:
  - name: configure rsync server
    copy:
      src: "{{ item.src }}"
      dest: "/etc/{{ item.dest }}"
      mode: "{{ item.mode }}"
      state: present
    with_items:
      - { src: "rsync.conf",dest: "rsync.conf",mode: "0644"}
      - { src: "rsync.passwd",dest: "rsync.passwd",mode: "0600"}
CAT_END

 

posted @ 2023-05-13 16:42  小粉优化大师  阅读(55)  评论(0编辑  收藏  举报