Ansible Conditionals & Loops

 一、條件語句

    條件判斷語句,就是根據某些變量的值來控制Ansible的執行流程。控制某些主機執行某些操作與不執行某些操作。根據某些操作結果,判斷是否執行其它操作等等。

    Ansible的條件判斷語句只有 when 語句,結合變量使用才能顯示出它的價值。when的用法:在想要進行判斷的語句下面添加when語句即可進行條件判斷.

二、示例

支持判斷的操作符

1、比較操作符

       ==       !=       >       >=       <       <=

2、邏輯運算符

       and       or       not

tasks:                #簡單的判斷
   - name: "shutdown Debian flavored systems"
     command: /sbin/shutdown -t now
     when: ansible_os_family == "Debian"
tasks:                 #組合形式的判斷
  - name: "shutdown CentOS 6 and Debian 7 systems"
    command: /sbin/shutdown -t now    
    when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
          (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")
tasks:                   #基于某些task的結果,執行相應的task
  - command: /bin/false
    register: result   
    ignore_errors: True
  - command: /bin/something
    when: result|failed
  - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped
tasks:                      #如果一些變量沒有定義,可以使用Jinja2的define測試。,來執行一些操作
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined      
 
    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined
tasks:               #有時一些變量的返回結果是字符串,但是你想對它做一些數學運算
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6
---              #對是否執行一些外部任務進行條件判斷
- hosts: local
  vars:
   test: true
 
  tasks:
  - name: Test test
    debug: msg="Hello When"
    when: test
 
  - include: pre.yml         #根據條件判斷,是否include某個外部任務文件。
    when: test           
 
  roles:
    - { role: /home/aheahe/roles/test, when: test }   #結合條件判斷,是否加載某個Role

 

可以看出條件判斷主要就是結合變量使用。

循環

一、簡介    

      通常一個任務會做很多事情,如創建大量的用戶,安裝很多包,或重復的輪詢特定的步驟,直到某種結果條件為止,Ansible為我們提供了此支持。下面是關于循環的一些語句。

 

with_items     #標準循環

with_nested    #嵌套循環

with_dict          #字典循環(Looping over hashed)

with_file       #循環文件

with_fileglob    #通配符循環文件

with_together    #循環映射

with_subelements  #子元素循環

with_sequence      #生成一系列的數字

with_random_choice   #任意選擇

#with_first_found      #選擇第一個找到的,不會用

with_lines          #循環程序執行的輸出信息with_items:{{command_result.stdout_lines}}

with_flattened      #循環列表中的列表的item

 

二、實例

---
- hosts: local                        #with_item 和 with_nested 用法
  vars:
    Sta: false
    User: [ "Aheahe","yunzhonghe" ]
  tasks:
  - name: Standard Loops
    debug: msg="{{ item.name }},{{ item.fun }}"
    with_items:                  #生成標準循環
     - { name: Loops, fun: xx }
     - { name: Conditional, fun: yy }
    when: Sta
  - name: Nested Loops
    debug: msg= "name={{ item[0] }},priv={{ item[1] }}"
    with_nested:                  #嵌套循環
     - "{{ User }}"                #這里的User 可以直接使用列表。
     - [ "Student","Engineer","Friends" ]

---
- hosts: local          #with_dict 用法
#  vars_files:
#    hash.yml
  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              #循環列表可以查看輸出信息。以獲取結果

 

---
- hosts: local                 #with_file 與 with_fileglob 用法。
  vars:
    test_file: false
  tasks:
  - name: test file
    shell: echo {{ item }}
    with_file:         #循環文件的內容
     - test                          #test文件里面為任意內容。
     - test1
    when: test_file
 
  - name: Test file Glob
    shell: echo {{ item }}
    with_fileglob:     #循環文件的通配符。
    - /home/aheahe/playbook/*

 

---
- hosts: local                 #with_together用法
  vars:
    alpha: [ 'a', 'b', 'c', 'd' ]
    numbers:  [ 1, 2, 3, 4 ]
    test: [ 'A', 'B', 'C', 'D' ]
  tasks:
   - debug: msg="{{ item.0 }} and {{ item.1 }} and {{ item.2 }}"
     with_together:                #循環映射信息
       - "{{alpha}}"
       - "{{numbers}}"
       - "{{test}}"

 

---
- hosts: local         #with_subelement用法
  vars:
    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"
  tasks:
  - name: Test1
    shell: echo "name={{ item.name }}"
    with_items: "{{users}}"
  - name: Test2
    shell: echo "User={{ item.0.name }},key={{ item.1 }}"
    with_subelements:         #循環子元素。
    - users
    - authorized

 

---
- hosts: local
  tasks:
  - name: Learn loop sequence
    debug: msg={{ item }}
    with_sequence: start=0 end=6 stride=2

 

---
- hosts: local                 # with_random_choice 用法
  tasks:
  - name: Learn Random
    debug: msg={{ item }}
    with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

 

---
- hosts: local         #with_lines 用法
  tasks:
  - name: test result
    shell: echo {{ item }}
    with_lines: /bin/df -Th
 
- name: flattened loop demo                       #with_flatted用法
  yum: name={{ item }} state=installed
  with_flattened:
     - "{{packages_base}}"
     - "{{packages_apps}}"
----
# file: roles/foo/vars/main.yml
packages_base:
  - [ 'foo-package', 'bar-package' ]
packages_apps:
  - [ ['one-package', 'two-package' ]]
  - [ ['red-package'], ['blue-package']]

原創文章,作者:艾賀,如若轉載,請注明出處:http://www.www58058.com/9446

(1)
艾賀艾賀
上一篇 2015-11-19
下一篇 2015-11-23

相關推薦

  • Linux安全和openssl、gpg加密

                     Linux安全和openssl、gpg加密 本章內容: 安全機制 對稱加密 不對稱加密 散列算法 PKI和CA openssl 證書管理 gpg   加密需要: 不加密的流量易受攻擊性 密碼/數據嗅探 數據操作 驗證操作 相當…

    系統運維 2016-10-09
  • 馬哥教育網絡21期+第二周練習博客

    1、Linux上的文件管理類命令都有哪些,其常用的使用方法及其相關示例演示。 長用的文件管理類命令有cp(復制),mv(移動),rm(刪除)。接下來我將為大家一一講解。 復制命令:cp 在cp時要根據源和目的做出確認與調整; 命令格式:     cp [OPTION]… [-T] SO…

    Linux干貨 2016-07-22
  • DNS實驗

    本實驗需的注意問題:      1、運營商的服務器需要更改根指向服務器地址      2、根服務器上的配置文件/etc/named.conf需要將"."根區域禁用;      3、更改區域數據庫文件的屬組為named;c…

    Linux干貨 2016-12-12
  • rsyslog將日志記錄于MySQL中,并用loganalyzer進行分析日志

    1、首先來安裝lamp環境的支持,與其相關的軟件包      # yum -y install rsyslog-mysql mariadb-server php php-mysql php-gd httpd       說明:rsyslog-mysql在數據庫中生成一個庫文件,但這個文件需…

    Linux干貨 2016-10-23
  • bash腳本編程

    1、寫一個腳本,判斷當前系統上所有用戶的shell是否為可登錄shell;分別統計這兩類用戶的個數;通過字符串比較來實現; #!/bin/bash declare -i loginSum=0; declare -i nologinSum=0; for x in `cat /etc/passwd|cut -d: -f 7` do if [ “/sb…

    Linux干貨 2017-10-31
  • 哥是玩程序的

      下面一組有趣的Web示例,這些示例使用Web的一些很“土”控件做出一些很有趣的玩意兒。原來,編程是可以用來玩的,看看這些玩程序的人搞出的這些有意思的玩意,簡直是玩得太有意思了。不過,請注意,這些東西只能使用Chrome打開,不然,你看不到相關的效果。 用滾動條做的時間 http://toki-woki.net/p/scroll-clock/,下…

    Linux干貨 2015-04-01

評論列表(1條)

  • stanley
    stanley 2015-11-26 17:19

    向寫書的標準努力

欧美性久久久久