Skip to content

Instantly share code, notes, and snippets.

@developerinlondon
Created February 27, 2018 16:11
Show Gist options
  • Save developerinlondon/981321f7f20dc80037467a856ce27d4e to your computer and use it in GitHub Desktop.
Save developerinlondon/981321f7f20dc80037467a856ce27d4e to your computer and use it in GitHub Desktop.
useful ansible stuff
ansible-playbook install-jenkins.yml --list-tasks
ansible file directory layout
ansible/inventory/
Production (group: dc1,dc2)
development
staging
group_vars/
all.yml
webservers/
secrets.yml
host_vars/
Migrate_yaml_inventory.yml
- hosts: localhost
gather_facts: false
tasks:
- template:
src: dump_hosts_yaml.j2
dest: /tmp/hosts.yml
{% set builtins = [‘hostvars’, ‘vars’, .....] %}
{% set dumped_var = [] %}
{% for group in groups if group != ‘all’ %}
{{group}}:
{%for myhostvar in hostvars[host] if myhostvar not in builtins %}
{{ myhostvar}}:: {{hostvars[host] [myhostvar] | to_json }}
{% if loo.last %}{% do dumped_vars.append(host) %}{%endif %}
{% endfor %}
{% endfor %}
{% endfor %}
Varibale Sources
- role default
- inventory file vars
- inventory group_vars, host_vars
- playbook group_vars, host_vars
- host facts
- play vars, vars_prompt, vars_files
- registered vars
- set_facts
- role parameters and include vars
- block(only for tasks in block), task vars
- extra vars (CLI, global, precedence)
Single deployment script
#!/usr/bin/ansible-playbook
- hosts: localhost
vars_prompt:
- name: app_name
prompt: ” Which app do you want to deploy?”
default: mainapp
- name: app_version
prompt: “Choose version/tag (default HEAD)”
default: ‘HEAD’
tasks:
- git: repo=git@myreposerver/{{ app_name }} version= {{ app_version}}
Parallel playbook execution
V1
time ansible-playbook play?.yml
time parallel ansible-playbook () ::: play?.yml
time $( ls play?.yml| xargs -nl -P3 ansible-playbook)
- name: really trying hard to aviod shell scripts v2
hosts: localhost
gather_facts: false
tasks:
- shell: ansible-playbook play1.yml
async: 10000
poll: 0
- shell: ansible-playbook play2.yml
async: 10000
poll: 0
- name: really trying hard to aviod shell scripts v3
hosts: localhost
gather_facts: false
tasks:
- shell: ansible-playbook play{{item}}.yml
async: 10000
poll: 0
with_items: [1,2,3]
register: runplays
- async_status: jid={{runplays.results[item.index].ansible_job_id}}
register: jobs
until: jobs.finished
with_indexed_items: [1,2,3]
retries: 100
Include_role
- hosts: localhost
tasks:
- packages: name={{httpd}} state=latest
- Include_role:
name: webapp
tasks_from: install.yml
- service: name={{httpd}} state=started
- include_role:
name: webapp
tasks_from: configure.yml
vars_from: “{{ansible_os}}.yml”
with_items: “{{ applications }}”
Fun with Handlers
- host: all
tasks:
- name: configure nginx
template: src=nginx.j2 dest=/etc/nginx.conf
notify: restart_nginx_cluster
handlers:
- name: restart_nginx_cluster
service: name=uwcgi state=restarted
notify: restart_nginx
- name: restart_nginx
service: name=nginx state=restarted
- hosts: all
tasks:
- name: configure nginx
template: src=nginx.j2 dest=/etc/nginx.conf
notify: restart_nginx_cluster
handlers:
- name: restart_uwcgi
service: name=uwcgi state=restarted
listen: restart_nginx_cluster
- name: restart_nginx
service: name=nginx state=restarted
listen: restart_nginx_cluster
- hosts: all
tasks:
- name: configure nginx
template: src=nginx.j2 dest=/etc/nginx.conf
notify: restart_nginx_cluster
handlers:
- name: restart_nginx_cluster
include: nginx_cluster_restart.yml
static: no
Separate logic from variables
- name: clone student lesson app for a users
host: nodes
vars:
user_home: /home/{{ username }}
user_ssh: “{{ user_home }}/.ssh”
deploy_key: “{{user_ssh}}/id_rsa”
app_dest: “{{ user_home }}/exampleapp”
tasks:
- name: create ssh directory
file:
state: directory
path: “{{ user_ssh }}”
- name Set Deployment key
copy:
src: file/deploy_key
dest: “{{ deploy_key }}”
- name: clone repo
git:
dest: “{{ app_dest }}”
key_file: “{{ deploy_key }}”
repo: [email protected]
accept_hostkey: yes
clone: yes
Ansible: properly copy local files within the target host
- set_fact:
rsync_dry_run: “--dry-run”
when: ansible_check_mode
- name: copy files within target host
shell: rsync --itemize-changes --archive {{ rsync_dry_run | default(‘’) }} /src/directory/ /dest/directory/
# always run
check_mode: no
register: rsync_result
changed_when: rsync_result.stdout != ‘’
Check mode will show, whether the task is to change files, and files won’t be copied if they already are in place.
--itemize-changes makes rsync output a change-summary for every updated file.
Other options thay you may want to use with rsync in this task:
--update skip files that are never in destination
--ignore-existing do not update files that exist in destination
--checksum do not skip files based on mod-time and size, use checksum
print role name inside template
# Generated by ansible role: {{ role_path | regex_replace(‘^.*/([^/]+)$‘, ‘\\1’) }}
- name: added server host entry
lineinfile: >
dest=/etc/hosts
line=“{{ ansible_eth0[‘ipv4’][‘address’] }} {{ ansible_fqdn }} {{ ansible_hostname }}”
state=present
- name: “generate /etc/hosts.ansible file”
template: “src=etc/hosts.j2 dest=‘/etc/copyhosts.test’ owner=root group=root mode=0644"
tags: etc_hosts
- name: “generate /etc/hosts.ansible file”
template: “src=etc/hosts.j2 dest=‘/etc/hosts.test’ owner=root group=root mode=0644"
tags: etc_hosts
# {{ ansible_managed }}
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
# Network nodes as generated through Ansible.
{% for host in play_hosts %}
{% if ‘ansible_eth0’ in hostvars[host] %}
{{ hostvars[host][‘ansible_eth0’][‘ipv4’][‘address’] }} {{ host }}
{% endif %}
{% endfor %}
#outputs for when
output.stdout.find(thomas)“” != -1
- name: App | Cloning repos + submodules
git: [email protected]:Organisation/{{ item.repo }}.git
dest={{ item.dest }}
accept_hostkey=yes
force=yes
recursive=no
key_file=/home/user/.ssh/id_rsa.github-{{ item.repo }}
with_items:
-
dest: “{{ destination }}”
repo: PrimaryRepo
-
dest: “{{ destination }}/app/core”
repo: SubmoduleRepo
register: db_migrations_result
changed_when: “not db_migrations_result.stdout|search(‘No migrations to execute’)”
when: test1.find(“World”) != -1
when: ansible_distribution == “Ubuntu” and docker_version.stdout.find(“1.10”) == -1 and pip_version.stdout.find(“8.“) == -1 and docker_py_version.stdout.find(“1.“) == -1
######################################
“- name: Generate new root password
  command: openssl rand -hex 7
creates: /root/.my.cnf
  register: mysql_new_root_pass
# If /root/.my.cnf doesn’t exist and the command is run
- debug: msg=“New root password is {{ mysql_new_root_pass.stdout }}”
  when: mysql_new_root_pass.changed
# If /root/.my.cnf exists and the command is not run
- debug: msg=“No change to root password”
  when: not mysql_new_root_pass.changed”
####################################################
- set_fact:
files: “{{ lookup(‘fileglob’,‘path/to/*.tar.gz’,wantlist=true) | reject(‘search’,‘useless’) | list }}”
---
- name: “Creating multiple by checking folders”
hosts: your_host_name
tasks:
- block:
- name: “Checking folders”
stat:
path: “{{item}}”
register: folder_stats
with_items:
- [“/var/www/f1”,“/var/www/f2",“/var/www/f3”,“/var/www/f4"]
- name: “Creating multiple folders without disturbing previous permissions”
file:
path: “{{item.item}}”
state: directory
mode: 0755
group: root
owner: root
when: item.stat.exists == false
with_items:
- “{{folder_stats.results}}”
#
Block styles with block chomping indicator (>-, |-, >+, |+)
You can control the handling of the final new line in the string, and any trailing blank lines (\n\n) by adding a block chomping indicator character:
>, |: “clip”: keep the line feed, remove the trailing blank lines.
>-, |-: “strip”: remove the line feed, remove the trailing blank lines.
>+, |+: “keep”: keep the line feed, keep trailing blank lines.
“Flow” scalar styles (, “, ’)
#
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment