Contents
template
今まで設定ファイルを使うときは基本ini_fileを使って置換したり、ローカルでファイルを作ってcopyしておりましたが、ansibleにはtemplateという機能があります。
簡単に言えばWebアプリケーションのようにHTMLテンプレートを用意し、その中に変数を埋め込むことができます。
例えばnginxをインストールするときは通常nginx自体もそうですが、それとともに/etc/nginx/conf.d/以下に設定ファイルも追加することが一般的だと思います。
1 2 3 4 5 6 7 8 9 10 |
- hosts: target remote_user: root tasks: - name: "install nginx" yum: name=nginx state=latest enablerepo=epel - template: src=./template/nginx/nginx.j2 dest=/etc/nginx/conf.d/{{item.hostname}}.conf owner=nginx group=nginx mode=0644 with_items: - { hostname: 'sample_host' } tags: nginx_conf |
templateタグをみていただければsrcがテンプレート自体 destがコピー先ということはわかるかと思います。
ここで.nginx.j2というテンプレートを用意する必要があります。
pythonでかかれていますが、設定ファイルに書くような情報は基本的には変数の置換ぐらいしか私はないため、ほとんどpythonがわからなくても行けます。
ちなみに私が書いたのは次のようなものです。ほとんどnginxの設定ファイルをそのまま持ってきて、動的な部分だけ変数にしました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
server { listen 80; server_name localhost; client_max_body_size 20M; #charset koi8-r; access_log /var/log/nginx/log/host.access.log main; location ~ /{{item.hostname}}/(.*)$ { root /var/nginx; index index.php index.html; try_files /{{item.hostname}}/$1 /{{item.hostname}}/$1/ /{{item.hostname}}/index.php?$1&$args; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; error_log /var/log/nginx/{{item.hostname}}.error.log; access_log /var/log/nginx/{{item.hostname}}.access.log; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root /var/nginx; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } |
一つのymlファイルの中でも特定のタスクだけを実行させたい or 逆に実行させたくないということはあるかと思います。
そんな時に使えるのがtagです。
上記のnginxの設定ファイル作成時に書いていますがtags: タグ名をつけておくことで、実行時に–tags タグ名でそのタスクだけを実行させることができます。飛ばす場合は–skip-tagsで飛ばせます。
yedit
ymlファイルを書くときに最初はvimで書いてたんですが、eclipseでもプラグインを入れることで書けます。
- ウィンドウタブから新規ソフトウェアのインストール選択
- 名前 yedit、ロケーション http://dadacoalition.org/yedit
- YEditをチェック、インストール
- 再起動後、設定でYEdit Referenceが入っていることを確認
- ymlファイルを開くときに右クリックで次で開くの時にYEdit YAML Editorを選択すればOK
yml最初書いていた時は構文のルールとかよくわからないで実行されずイライラしていたんでこれでsyntaxチェックとかしてくれるのがありがたいです。