Skip to content

Instantly share code, notes, and snippets.

@chroju
Last active January 30, 2016 08:14
Show Gist options
  • Select an option

  • Save chroju/a35a781f1ac9d15a9a81 to your computer and use it in GitHub Desktop.

Select an option

Save chroju/a35a781f1ac9d15a9a81 to your computer and use it in GitHub Desktop.
[CheatSheet] ansible

Ansible Cheat Sheet

commands

ansible-playbook

$ ansible-playbook -i inventory site.yml

grammer

with_items

- name: change config
  lineinfile: dest=/etc/example.conf regexp="{{ item.regexp }}" line="{{ item.line }}"
  with_items:
  - { regexp: '^sample one', line: '^sample two' }
  - { regexp: '^sample three', line: '^sample "{{ example_var}}"' }

modules

yum

- yum: name=foo state=present enablerepo=epel

service

- service: name=nginx state=restarted enabled=yes

git

- git: repo=https://github.com/chroju/dotfiles dest=/home/chroju/dotfiles 

copy

- copy: dest=/tmp/foo src=/localfiles/foo owner=root group=root mode=0600 force=yes

template

- template: dest=/tmp/foo src=foo.j2 owner=root group=root mode=0600 force=yes backup=yes
  • copyモジュールとの違いは内部で変数を使えること。

file

- file: path=/tmp/foo owner=root group=root mode=0644 recurse=yes state=directory
  • ファイルの所有者やモードを変更したり、シンボリックリンクを貼ったりするのに使う。
  • シンボリックリンクを貼る際はstate=link src=sourcefile
  • state=absentでファイルを消したり、state=touchで空ファイルを置いたりもできる。

unarchive

- unarchive: src=/tmp/foo dest=/usr/local/bar mode=0644 copy=no
  • デフォルトではローカルからリモートへの転送動作になるので、リモートサーバー内での解凍処理の場合はcopy=noを付ける。
  • srcにはhttp等を指定してダウンロードさせることも可能。その場合もcopy=no指定が要る。

lineinfile

- lineinfile: dest=/tmp/foo line="sample message" insertafter="before message" create=yes state=present backup=yes
  • insertafterは最後にマッチした文字列に対して適用される。デフォルトはEOF。同様にinsertbeforeも存在する。
  • 置換で使用する場合は置換対象をregexpパラメーターで指定する。後方参照を行いたい場合はbackrefs=yesとする。

debug

- shell: ls -la /var/log
  register: result
  
- debug: var=result
  • 変数等を標準出力上に展開し、デバッグ支援を行う。出力の指定にはvarmsgのいずれかを使用する。
  • varで指定した変数を出力する。
  • msgで出力する文字列を指定できる。

templateの書き方

default

変数が未定義の場合のデフォルト値を設定する。

{{ var | default('default value') }}

default(omit)を指定すると、変数未定義の場合にパラメーターそのものが除去される。

# Ansible Docsより抜粋
# この場合/tmp/bazのときのみmodeが設定される
- name: touch files with an optional mode
  file: dest={{item.path}} state=touch mode={{item.mode|default(omit)}}
  with_items:
    - path: /tmp/foo
    - path: /tmp/bar
    - path: /tmp/baz
      mode: "0444"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment