ansible のダウンロード処理のリトライ(と既存コードの書き換えスクリプト)
これは何
playbook の自動テストで各種パッケージダウンロードの処理がたまに落ちていた。コードの問題ではないところで落ちてjenkinsが赤くなると嫌なので出来るだけ通るようにしたい。 リトライ処理をいれて問題の緩和を図りたい。 微妙に詰まったのでメモを残しておく。
参考文献
- get_url のreturn valuesについて;http://docs.ansible.com/ansible/latest/get_url_module.html#return-values
- untilのところ: http://docs.ansible.com/ansible/latest/playbooks_loops.html#do-until-loops
- result|succeededのところ: http://docs.ansible.com/ansible/latest/playbooks_conditionals.html#the-when-statement
コード解説
- name: download nginx source become: no get_url: url: "http://nginx.org/download/nginx-{{ NGINX_VERSION }}.tar.gz" dest: "/usr/local/src" register: download_result until: download_result|succeeded retries: 3 delay: 5
until, reties はセットで書く必要がある。untilの記述がなければretiesは1になる。 untilでの判定をするためにregisterで変数にタスク実行結果を入れておく。
おまけ
既存コードの書き換えのためのスクリプト
沢山の場所を書き換えないといけないのでperlスクリプトを使った。
grep -r "get_url:" | awk -F':' '{print $1}' | sort | uniq | xargs perl -i -0pe 's/(get_url:(.*\n)+?)^\s*$/\1 register: download_result\n until: download_result|succeeded\n retries: 3\n delay: 5\n/m'
以下スクリプト解説のようなメモ書きのような。
基本的にyamlのブロックごとに改行を挟んでいるので、それを用いる。
オプション修飾子mは対象文字列が複数行である場合に使う。
以下のような構造のyamlになっていた場合に、^\s*$
で空行までのマッチになる。
ここで(.*\n)+?
に?をつけているのは最短一致のためで、これをつけないと最長一致になってしまって空行1までではなくて、いけるところまでいったところ(この場合は空行2)までマッチするので注意が必要。
- name: download nginx source become: no get_url: url: "http://nginx.org/download/nginx-{{ NGINX_VERSION }}.tar.gz" dest: "/usr/local/src" (空行1) - name: hoge piyo: fuga (空行2) - name: hoge piyo: fuga
便利ツール紹介
ところで、正規表現を最初からコマンドラインで書くのもありなのだけど、あまりにも辛いのでGUIツールを使うのがよい。以下のサイトが最高なのでみんな使うべき。 https://regex101.com/