Ansible snippets

# login as user ubuntu, use python3 and relogin as root
- hosts:
    - vm1
    - vm2
  become: yes
  vars:
    ansible_python_interpreter: /usr/bin/python3
    ansible_ssh_user: ubuntu
  tasks:
    - include: "{{ inventory_hostname }}.yml"
 
# show user and host
- debug:
    msg="{{ ansible_user_id }}@{{ inventory_hostname }}"
 
# show host groups
- debug:
    msg: "{{ group_names }}"
 
- debug:
    var: hostvars[inventory_hostname]
 
- debug:
    msg: "{{ ansible_system_vendor }}"
 
- debug:
    msg: "ansible_default_ipv4["address"]"
 
- debug:
    msg: "{{ vms | length }}"
 
- debug:
    msg="{{ playbook_dir }} / {{ inventory_dir }} / {{ role_path }}"
 
- name: Dictonary to list
  debug:
    msg="{{ my_packages | join(' ') }}"
 
- name: set default value
- set_facts:
    ansible_ssh_user: "{{ lookup('env', 'SSH_USER') | default('foo', true) }}"
 
  vars:
    os_cloud: "{{ lookup('env','OS_CLOUD') | default('dev-foo', true) }}"
    os_user: "{{ os_cloud.split('-')[1] | default(lookup('env','OS_USERNAME'), true) | default(lookup('env','USER'), true)}}"
 
# check if directory exists
- block:
  - name: Remove default configuration
    file:
      state: absent
      path: /etc/icinga/objects
    when: check_path.stat.exists == false
 
  - name: Deploy configuration
    git:
      repo: git@git.example.com:foo/icinga.git
      dest: /etc/icinga/objects
      accept_hostkey: yes
    notify: icinga restart
 
  when: check_path.stat.exists == false
 
- name: Directory exists already
  debug:
    msg: "Do something else..."
  when: check_path.stat.exists
 
- name: get env variable
  debug:
    msg:  "{{ lookup('env','HOME') }}"
 
- name: Copy directory on remote when not already exists
  command: cp -a /tmp/foo /tmp/bar
  args:
    creates: /tmp/bar
 
# check if package installed
- name: Check if package is already installed
  command: dpkg-query -W package_name
  register: dpkg_query
  changed_when: false
  failed_when: dpkg_query.rc > 1
- name: Install package
  package:
    name: package_name
  when: dpkg_query.rc > 0
 
# if / else condition
- set_fact:
    second_var: "{{ 'foo' if first_var != 'stable' else 'bar' }}" 
 
- set_fact:
    second_var: "{{ ( first_var != 'stable' ) | ternary('foo','bar') }}" 
 
- name: Configure locale
  locale_gen:
    name: "{{ item }}"
  with_items:
    - de_DE.UTF-8
    - en_US.UTF-8
 
# get distribution
- setup:
    filter: ansible_distribution
- debug:
    msg: "{{ ansible_distribution }}"
 
- name: Configure timezone
# todo: (require dbus package)
#  timezone:
#    name: "Europe/Berlin"
#    hwclock: local
  copy:
    content: "Europe/Berlin"
    dest: /etc/timezone
  tags: timezone
 
- name: Add directory to PATH variable
  lineinfile:
    dest: "/home/foo/.profile"
    backrefs: yes
    regexp: 'PATH=(["]*)((?!.*?/home/foo/bin).*?)(["]*)$'
    line: 'PATH=\1\2:/home/foo/bin\3'
 
- name: Generate SSH key for a user with customized comment
  user:
    name: nagios
    generate_ssh_key: yes
    ssh_key_comment: nagios@{{ inventory_hostname }}
 
- name: check current timezone
  shell: cat /etc/timezone
  register: get_timezone
- name: set /etc/timezone
  shell: echo "{{ timezone }}" > /etc/timezone
  when: '"{{ timezone }}" not in get_timezone.stdout'
  notify: update tzdata
 
- name: Deploy SSH key to inventory groups
  authorized_key:
    user: root
    key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
  delegate_to: "{{ item }}"
  with_items: "{{  }}"
  with_items:
    - "{{ groups.webserver }}"
    - "{{ groups['proxy-server'] }}"
  ignore_errors: yes
 
#  when: inventory_hostname in groups['www']
 
- name: Get parameter from ini file from localhost
  debug:
    msg: "User in production  is {{ lookup('ini', 'user section=production  file=users.ini') }}"
 
- name: Remove /foo/bar if its a directory
  stat:
    path: /foo/bar
  register: path
- file:
    path: /foo/bar
    state: absent
  when: path.stat.isdir is defined and path.stat.isdir
 
 
- name: Configure network
  copy:
    content: |
      auto lo
      iface lo inet loopback
 
      auto eth0
      iface eth0 inet static
      address {{ ansible_default_ipv4.address }}
      netmask 255.255.255.0
      gateway 10.0.3.254
    dest: /etc/network/interfaces
 
- name: Configure DNS
  copy:
    content: |
      nameserver 10.0.3.1
      domain example.com
      search example.com
    dest: /etc/resolv.conf
 
- name: get public IP address from ipify.org
  ipify_facts:
- debug:
    msg: "{{ ipify_public_ip }}"
 
# list VMs
- name: List VMs
  virt:
    command: list_vms
  register: vms
- debug:
    msg: "{{ item }}"
  with_items: "{{ vms.list_vms }}"
 
- debug:
    msg: "{{ hostvars['www.example.com']['ansible_ssh_host_key_ecdsa_public'] }}"
 
- include_tasks: prerequisites_{{ ansible_os_family | lower }}.yml
 
# Create LV
- stat:
    path: /dev/vg1/images
  register: p
- name: Create LV /dev/vg1/images
  lvol:
    vg: vg1
    lv: images
#    size: "100%FREE"
    size: 430G
  when: not p.stat.exists
 
# Create filesystem
- name: Format /dev/vg1/images
  filesystem:
    fstype: ext4
    dev: /dev/vg1/images
 
# Create mountpoint for filesystem
- name: Configure /etc/fstab
  mount:
    path: /var/lib/libvirt/images
    src: /dev/vg1/images
    fstype: ext4
    state: mounted
 
# ipaddr filter
- hosts: localhost
  vars:
    my_ip: "{{ ansible_default_ipv4.network }}/{{ ansible_default_ipv4.netmask }}"
  tasks:
    - debug: msg="network {{ my_ip | ipaddr('network') }}"
    - debug: msg="netmask {{ my_ip | ipaddr('netmask') }}"
 
# get host ip addresses
    - debug: var=ansible_all_ipv4_addresses
    - debug: var=ansible_default_ipv4.address
 
- debug: msg="{{ ansible_virtualization_type }}"
# lxc
 
# override systemd service
- name: Create /etc/systemd/system/apache2.service.d directory
  file:
    path: /etc/systemd/system/apache2.service.d
    state: directory
    owner: root
    group: root
    mode: 0755
 
- name: Override apache2.service
  ini_file:
    dest: /etc/systemd/system/apache2.service.d/override.conf
    section: "{{ item.section }}"
    option: "{{ item.option }}"
    value: "{{ item.value }}"
    no_extra_spaces: yes
  with_items:
    - { section: Service, option: PIDFile, value: "/var/run/apache2/apache2.pid" }
    - { section: Service, option: Restart, value: "on-failure" }
    - { section: Service, option: RestartSec, value: "30s" }
  notify:
    - systemctl daemon-reload
 
- name: Check if the disk is partitioned and also ignore sda
  stat: path=/dev/{{item}}1
  with_items: disk_var
  when: item != 'sda'
  register: device_stat
- name: Create GPT partition table
  command: /sbin/parted -s /dev/{{ item.item }} mklabel gpt
  with_items: device_stat.results
  when:
    - not item | skipped
    - item.stat.exists == false
 
- name: Remove all cronjobs
  shell: crontab -r
  become: true
  become_user: "{{ default_user }}"
  ignore_errors: yes
 
- set_fact:
    dl_url: http://git.example.com/script.sql
- name: get sql
  uri:
    method: GET
    headers:
      PRIVATE-TOKEN: "your_private_token"
    url: "{{ dl_url }}"
    dest: /tmp/bar.sql
  environment:
    http_proxy: http://router.example.com:3128
 
- name: Check if the disk is partitioned and also ignore sda
  stat: path=/dev/{{item}}1
  with_items: disks
  when: item != "sda"
  register: device_stat
- name: Create GPT partition table
  command: /sbin/parted -s /dev/{{ item.item }} mklabel gpt
  with_items: device_stat.results
  when:
    - not item | skipped
    - item.stat.exists == false
 
- name: Create rsnapshot daily backup
  cron:
    name: rsnapshot daily backup
    hour: 1
    minute: 25
    job: /usr/bin/rsnapshot daily
 
- name: Create rsnapshot weekly backup
  cron:
    name: rsnapshot weekly backup
    hour: 2
    minute: 25
    weekday: 1
    job: /usr/bin/rsnapshot weekly
 
 - name: Create rsnapshot monthly backup
  cron:
    name: rsnapshot monthly backup
    hour: 3
    minute: 25
    day: 1
    job: /usr/bin/rsnapshot monthly
 
# dconf (read values with "dconf watch /" command)
# https://docs.ansible.com/ansible/2.4/dconf_module.html
- name: Read currently available keyboard layouts in Gnome
  dconf:
    key: /org/gnome/desktop/input-sources/sources
    state: read
  register: dconf
  become: yes
  become_user: "{{ default_user }}"
 
- debug:
    msg: "{{ dconf }}"
 
- name: Configure Gnome
  dconf:
    key: "{{ item.key }}"
    value: "{{ item.value }}"
  with_items:
    - { key: "/com/canonical/indicator/datetime/show-date", value: "true" }
  become: yes
  become_user: "{{ default_user }}"
 
# all nodes except
- name: show all the hosts matching the pattern, ie all but the group www
  debug:
    msg: "{{ item }}"
  with_inventory_hostnames:
    - all:!www
 
# format json output
- debug:
    msg: "{{ hostvars[inventory_hostname] | to_nice_json }}"
 
 
- name: Force reboot on HP Gen8 nodes
  shell: "{{ item }}"
  async: 1
  poll: 0
  with_items:
    - sync
    - sleep 2 && echo 1 > /proc/sys/kernel/sysrq
    - sleep 2 && echo b > /proc/sysrq-trigger
  when: ansible_product_name == "ProLiant DL380p Gen8"
 
- name: Print item index
  debug:
    msg: "{{ item }} with index {{ idx + 1 }}"
  loop:
    - a
    - b
    - c
  loop_control:
    index_var: idx
 
- name: Prepare Nginx VHosts
  copy:
    content: |
      server {
          listen 80;
          listen [::]:80 ;
          server_name {% if idx == 0 %}_{% else %}{{ item }}{% endif %};
 
          root /var/www/{{ item }}/html;
          index index.html;
 
          location / {
              try_files $uri $uri/ =404;
          }
      }
    dest: /etc/nginx/sites-available/{{ item }}
    owner: root
    group: root
    mode: 0644
  loop: "{{ vhosts }}"
  loop_control:
    index_var: idx
 
# test-me:
{{ ansible_env.HOME }}
 
"ansible_distribution_release": "bionic", 
"ansible_distribution_major_version": "18", 
"ansible_distribution_version": "18.04", 
 
addresses: [{{ ansible_default_ipv4.address }}/24]
#gateway4: {{ ansible_default_ipv4.address.split('.')[0:3] | join('.') }}.1
gateway4: {{ ansible_default_ipv4.gateway }}
 
# dns
# sudo apt install -y python-dnspython
- debug:
      msg: "{{ lookup('dig','www.example.com' ) }}"
 
# nginx
- name: Configure nginx sites
  copy:
    content: |
      server {
          listen 80 default_server;
          listen [::]:80 default_server;
          server_name _;
 
          root /var/www/html;
          index index.html;
 
          location / {
              try_files $uri $uri/ =404;
              autoindex on;
          }
 
          location ~ /\.git {
            deny all;
          }
      }
    dest: /etc/nginx/sites-available/default
    owner: root
    group: root
    mode: 0644
  notify: service nginx restart
 
# calculate ip
- hosts: localhost
  vars:
    mgmt_net: 10
    ipmi_net: 20
    ip: "{{ lookup('dig', 'www.example.com').split('.') }}"
  tasks:
    - debug:
        msg: "{{ ip[0] }}.{{ ipmi_net }}.{{ ip[2] }}.{{ ip[3] }}"
    - debug:
        msg: "{{ lookup('dig', 'www.example.com') | replace('.{{ mgmt_net }}.', '.{{ ipmi_net }}.') }}"
 
- name: Upload file into s3 object storage
  os_object:
    cloud: "{{ os_cloud }}"
    name: fstab
    container: config
    filename: /etc/fstab
 
- name: Install a deb package dirctly from the internet
  apt:
    deb: https://example.com/python-ppq_0.1-1_all.deb
 
- name: Update APT cache and remove useless packages / dependencies
  apt:
    update_cache: yes
    autoclean: yes
    autoremove: yes