Ansible 小手冊(cè)系列 十四(條件判斷和循環(huán))

條件判斷


When 語(yǔ)句

在when 后面使用Jinja2 表達(dá)式禽笑,結(jié)果為True則執(zhí)行任務(wù)永丝。

tasks:
  - name: "shut down Debian flavored systems"
    command: /sbin/shutdown -t now
    when: ansible_os_family == "Debian"

若操作系統(tǒng)是Debian 時(shí)就執(zhí)行關(guān)機(jī)操作

可以對(duì)條件進(jìn)行分組在比較漱办。

tasks:
  - name: "shut down 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")

可以使用列表形式來(lái)表示條件為and的關(guān)系

tasks:
  - name: "shut down CentOS 6 systems"
    command: /sbin/shutdown -t now
    when:
      - ansible_distribution == "CentOS"
      - ansible_distribution_major_version == "6"

使用jinja2過(guò)濾器

tasks:
  - command: /bin/false
    register: result
    ignore_errors: True

  - command: /bin/something
    when: result|failed

  - command: /bin/something_else
    when: result|succeeded

  - command: /bin/still/something_else
    when: result|skipped

忽略一個(gè)語(yǔ)句的錯(cuò)誤,然后決定基于成功或失敗有條件地做一些事情。

字符串轉(zhuǎn)換為數(shù)字型再去比較

tasks:
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6

使用變量進(jìn)行判斷

vars:
  epic: true
tasks:
    - shell: echo "This certainly is epic!"
      when: epic
tasks:
    - shell: echo "This certainly isn't epic!"
      when: not epic

判斷變量是否定義

tasks:
    - 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

與循環(huán)一起使用

tasks:
    - command: echo {{ item }}
      with_items: [ 0, 2, 4, 6, 8, 10 ]
      when: item > 5

依次遍歷列表扫茅,當(dāng)列表里得數(shù)字大于5時(shí)執(zhí)行任務(wù)

- command: echo {{ item }}
  with_items: "{{ mylist|default([]) }}"
  when: item > 5
- command: echo {{ item.key }}
  with_dict: "{{ mydict|default({}) }}"
  when: item.value > 5

當(dāng)變量不存在時(shí),直接跳過(guò)

使用自定義的facts值做判斷

tasks:
    - name: gather site specific fact data
      action: site_facts
    - command: /usr/bin/thingy
      when: my_custom_fact_just_retrieved_from_the_remote_system == '1234'

角色包含使用when

- include: tasks/sometasks.yml
  when: "'reticulating splines' in output"
- hosts: webservers
  roles:
     - { role: debian_stock_config, when: ansible_os_family == 'Debian' }

基于變量選擇文件和模板

- name: template a file
  template: src={{ item }} dest=/etc/myapp/foo.conf
  with_first_found:
    - files:
       - {{ ansible_distribution }}.conf
       - default.conf
      paths:
       - search_location_one/somedir/
       - /opt/other_location/somedir/

使用注冊(cè)變量判斷

- name: test play
  hosts: all

  tasks:

      - shell: cat /etc/motd
        register: motd_contents

      - shell: echo "motd contains the word hi"
        when: motd_contents.stdout.find('hi') != -1

failed_when

滿足條件時(shí)育瓜,使任務(wù)失敗

  tasks:
    - command: echo faild.
      register: command_result
      failed_when: "'faild' in command_result.stdout"
   - debug: msg="echo test"

還可以寫成這樣

  tasks:
    - command: echo faild.
      register: command_result
      ignore_errors: True

    - name: fail the echo
      fail: msg="the command failed"
      when: "'faild' in command_result.stdout"
    - debug: msg="echo test"

changed_when

更改任務(wù)的狀態(tài)葫隙。

- name: Install dependencies via Composer.
  command: "/usr/local/bin/composer global require phpunit/phpunit --prefer-dist"
  register: composer
  changed_when: "'Nothing to install or update' not in composer.stdout"

當(dāng)使用PHP Composer作為安裝項(xiàng)目依賴項(xiàng)的命令時(shí),知道什么時(shí)候是有用的Composer安裝了一些東西爆雹,或什么都沒(méi)有改變停蕉。

循環(huán)


標(biāo)準(zhǔn)循環(huán)
添加多個(gè)用戶

- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - testuser1
     - testuser2

添加多個(gè)用戶,并將用戶加入不同的組內(nèi)钙态。

- name: add several users
  user: name={{ item.name }} state=present groups={{ item.groups }}
  with_items:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }

嵌套循環(huán)

分別給用戶授予3個(gè)數(shù)據(jù)庫(kù)的所有權(quán)限

- 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' ]

遍歷字典

輸出用戶的姓名和電話

 tasks:
  - name: Print phone records
    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'} }

并行遍歷列表

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

如果列表數(shù)目不匹配慧起,用None補(bǔ)全

遍歷列表和索引

  - name: indexed loop demo
    debug: "msg='at array position {{ item.0 }} there is a value {{ item.1 }}'"
    with_indexed_items: [1,2,3,4]

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

遍歷文件列表的內(nèi)容

---
- hosts: all
  tasks:
       - debug: "msg={{ item }}"
      with_file:
        - first_example_file
        - second_example_file

遍歷目錄文件
with_fileglob匹配單個(gè)目錄中的所有文件册倒,非遞歸匹配模式蚓挤。

---
- hosts: all
  tasks:
    - file: dest=/etc/fooapp state=directory
    - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
      with_fileglob:
        - /playbooks/files/fooapp/*

當(dāng)在role中使用with_fileglob的相對(duì)路徑時(shí),Ansible解析相對(duì)于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的值

重試循環(huán) until

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

"重試次數(shù)retries" 的默認(rèn)值為3灿意,"delay"為5。

查找第一個(gè)匹配文件

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

依次尋找列表中的文件崇呵,找到就返回缤剧。如果列表中的文件都找不到,任務(wù)會(huì)報(bào)錯(cuò)域慷。

隨機(jī)選擇with_random_choice

隨機(jī)選擇列表中得一個(gè)值

- debug: msg={{ item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

循環(huán)程序的結(jié)果

  tasks:
  - debug: "msg={{ item }}"
    with_lines: ps aux 

循環(huán)子元素

定義好變量

#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文件的內(nèi)容
with_subelements 遍歷哈希列表荒辕,然后遍歷列表中的給定(嵌套)的鍵。

在序列中循環(huán)with_sequence

with_sequence以遞增的數(shù)字順序生成項(xiàng)序列犹褒。 您可以指定開始抵窒,結(jié)束和可選步驟值。
參數(shù)應(yīng)在key = value對(duì)中指定叠骑。 'format'是一個(gè)printf風(fēng)格字符串李皇。

數(shù)字值可以以十進(jìn)制,十六進(jìn)制(0x3f8)或八進(jìn)制(0600)指定宙枷。 不支持負(fù)數(shù)掉房。

---
- hosts: all

  tasks:

    # 創(chuàng)建組
    - group: name=evens state=present
    - group: name=odds state=present

    # 創(chuàng)建格式為testuser%02x 的0-32 序列的用戶
    - user: name={{ item }} state=present groups=evens
      with_sequence: start=0 end=32 format=testuser%02x

    # 創(chuàng)建4-16之間得偶數(shù)命名的文件
    - file: dest=/var/stuff/{{ item }} state=directory
      with_sequence: start=4 end=16 stride=2

    # 簡(jiǎn)單實(shí)用序列的方法:創(chuàng)建4 個(gè)用戶組分表是組group1 group2 group3 group4
    - group: name=group{{ item }} state=present
      with_sequence: count=4

隨機(jī)選擇with_random_choice
隨機(jī)選擇列表中得一個(gè)值

- debug: msg={{ item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

合并列表

# 安裝所有列表中的軟件
- name: flattened loop demo
  yum: name={{ item }} state=installed
  with_flattened:
     - [ 'foo-package', 'bar-package' ]
     - [ ['one-package', 'two-package' ]]
     - [ ['red-package'], ['blue-package']]

注冊(cè)變量使用循環(huán)

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

循環(huán)主機(jī)清單

# 輸出所有主機(jī)清單里的主機(jī)
- debug: msg={{ item }}
  with_items: "{{ groups['all'] }}"
# 輸出所有執(zhí)行的主機(jī)
- debug: msg={{ item }}
  with_items: play_hosts

#輸出所有主機(jī)清單里的主機(jī)
- debug: msg={{ item }}
  with_inventory_hostnames: all

# 輸出主機(jī)清單中不在www中的所有主機(jī)
- debug: msg={{ item }}
  with_inventory_hostnames: all:!www

改變循環(huán)的變量項(xiàng)

# 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

更多文章請(qǐng)看 Ansible 專題文章總覽

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市慰丛,隨后出現(xiàn)的幾起案子圃阳,更是在濱河造成了極大的恐慌,老刑警劉巖璧帝,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捍岳,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)锣夹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門页徐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人银萍,你說(shuō)我怎么就攤上這事变勇。” “怎么了贴唇?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵搀绣,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我戳气,道長(zhǎng)链患,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任瓶您,我火速辦了婚禮麻捻,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘呀袱。我一直安慰自己贸毕,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布夜赵。 她就那樣靜靜地躺著明棍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪寇僧。 梳的紋絲不亂的頭發(fā)上摊腋,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音婉宰,去河邊找鬼歌豺。 笑死推穷,一個(gè)胖子當(dāng)著我的面吹牛心包,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播馒铃,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蟹腾,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了区宇?” 一聲冷哼從身側(cè)響起娃殖,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎议谷,沒(méi)想到半個(gè)月后炉爆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年芬首,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了赴捞。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡郁稍,死狀恐怖赦政,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情耀怜,我是刑警寧澤恢着,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站财破,受9級(jí)特大地震影響掰派,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜狈究,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一碗淌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧抖锥,春花似錦亿眠、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至拯勉,卻和暖如春竟趾,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背宫峦。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工岔帽, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人导绷。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓犀勒,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親妥曲。 傳聞我的和親對(duì)象是個(gè)殘疾皇子贾费,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容