- block: - name: Get docker version shell: "{{ cmd }}" register: result_docker_version changed_when: no ignore_errors: yes vars: cmd: !unsafe docker version --format '{{.Server.Version}}'
from ansible.plugins.action import ActionBase import jinja2 class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): result = super(ActionModule, self).run(tmp, task_vars) return dict(jinja_version=jinja2.__version__)
- hosts: localhost connection: local gather_facts: no tasks: - action: jin_ver register: result - debug: msg="{{ result }}"
ansible-playbook playbook.yml ... TASK [debug] ************************************************************************************************************************************ ok: [localhost] => { "msg": { "changed": false, "failed": false, "jinja_version": "2.7.2" } }
- hosts: localhost gather_facts: no connection: local vars: listvar: - Node: Node: test-c Id: c - Node: Node: test-b Id: b - Node: Node: test-a Id: a dictvar: NodeA: 10 NodeB: 1 NodeC: 2 tasks: - name: sort of Node.Node debug: msg: "{{ listvar | sort(attribute='Node.Node') }}" - name: dictsort of value debug: msg: "{{ dictvar | dictsort(by='value') }}"
ansible-playbook playbook.yml ... TASK [dictsort of value] ************************************************************************************************************************ ok: [localhost] => { "msg": [ [ "NodeB", 1 ], [ "NodeC", 2 ], [ "NodeA", 10 ] ] } TASK [dictsort of value] ************************************************************************************************************************ ok: [localhost] => { "msg": [ [ "NodeB", 1 ], [ "NodeC", 2 ], [ "NodeA", 10 ] ] } ...
{% set list_var1 = ['aa','bb','cc'] %} {% for var1 in list_var1 if var1 == 'aa' %} {{ var1 }} {% endfor %}
regex_search, regex_findallが使えるようだ
lineinfile: dest=/tmp/example.conf line={{ item }} with_items: - 'example_enabled={{ "yes" if example_enabled else "no" }}'
ini_file: dest: /etc/yum.conf section: main option: proxy value: "{{ yum_proxy }}" state: "{{ 'present' if yum_proxy != None else 'absent' }}" backup: yes
Whitespace Control - Jinja2 Documentation (2.10)
debug: msg="{{ item.state | default('present') }}"
- name: config file template: src: example.conf.j2 dest: /etc/example/example.conf owner: root group: root mode: 0644 backup: yes
{{ ansible_distribution }}
cat roles/test1/tasks/main.yml - template: src=roles/test2/templates/text2.j2 dest=/tmp/test2.conf mode=0644
# {{ ansible_managed }}
{% if item1 != "" %} item1={{ item1 }}{% endif %}{% if item2 != "" %} item2={{ item2 }} {% endif %}
item1=aaa item2=bbb
{% if 'description:' in item.stdout %} replace: description {% else %} add: description {% endif %}
{{ 'replace' if 'description:' in item.stdout else 'add' }}: description