to run some ansible code, you use a playbook:
ansible-playbook [-i ] [--extra-vars "host_list=]
where = client1,client2,
subset (section of inventory file)
localhost
all
you can also run ansible one-offs:
ansible -m [-i ]
run playbook on other machines for testing:
ansible-playbook -i --ask-pass --become-user
sample playbook:
- hosts: '{{ host_list }}'
remote_user: '{{ remote_user }}'
become: yes
become_method: sudo
gather_facts: yes
vars:
remote_user: root
host_list: all
tasks:
- name: dump facts to var
setup:
register: dump_facts
- name: see what the dump_facts register now contains
debug:
msg:
- " '{{ dump_facts }}' "
- name: write facts to file ON LOCAL SERVER
local_action:
module: blockinfile
path: "/path/to/dump_facts"
block: "{{ dump_facts |string }}"
create: yes
precede any of the preceding ansible-running commands with:
ANSIBLE_HOST_KEY_CHECKING=False
can set defaults in: /etc/ansible/ansible.cfg
inventory = /path/to/default/inventory/file
host_key_checking = False
ansible environment variables succ
there are no sane options for where to put them (relative to the ansible playbook plz? NO)
look up list of optiions, may be updated by the time you read this
also the current dir "ansible.cfg" fails if dir is world-writeable
copy a default config file from /etc/ansible/ansible.cfg and edit as liked
set environment variables in playbook:
environment:
ANSIBLE_HOST_KEY_CHECKING: False
vars:
tasks:
- name: test env vars
shell: "echo $ANSIBLE_HOST_KEY_CHECKING"
register: outcome
- name: print outcome to screen for viewing
debug:
msg: - " {{ outcome.stdout }} "
do thing if variable = value, or based on outcome of command:
vars:
do_thing: False
tasks:
- name: register outcomes of dependencies
local_action: command grep -x ""
register: outcome
- name: do thing if
systemd:
name: reboot.service # also works with timers
state: started
when: outcome.rc == 0 and do_thing|bool == True
fail when, and math in ansible:
vars:
var1: 5
tasks:
- name: fail when
fail:
msg:
- "fail because result is {{ ( var1|int - ansible_date_time.epoch|int )|abs > 300 }} "
when: ( epoch_base|int - ansible_date_time.epoch|int )|abs > 300
misc notes:
add a plain "command" thingy under local_action, very useful for ex.: grep
and if that grep fails to find smth, will cause the ansible play to fail! useful!