Skip to content

Instantly share code, notes, and snippets.

@swdream
Last active August 27, 2018 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swdream/0ac6296eca1f36ad6ba7a68c4c64d8a3 to your computer and use it in GitHub Desktop.
Save swdream/0ac6296eca1f36ad6ba7a68c4c64d8a3 to your computer and use it in GitHub Desktop.

Concepts:

  • groups: set of hosts
  • facts: contains all info about remote host.
  • Ansible facts are a way of getting data about remote systems for use in playbook variables.
1. these operating systems, Ansible will fallback into using a high-quality Python implementation of OpenSSH called ‘paramiko’.
2. By default, ansible read remote hosts in /etc/ansible/hosts, it is an inventory file.
192.0.2.50
aserver.example.org
bserver.example.org

using --private-key option to specify a pem file (private key).

ping remote hosts:

$ ansible all -m ping -u bruce
3. using -e to set parameters:
$ ansible localhost -m ping -e 'ansible_python_interpreter="/usr/bin/env python"'
4. Ansible have some connection type:
  • SSH
  • local: control localhost itself.
  • docker: connect to containers.

I. Inventory

Default, inventory file: /etc/ansible/hosts. we can select inventory file using -i option.

Dynamic inventory: we can user many inventory file at the same time and pull inventory from dynamic or cloud source or different format (ini, yaml ...)

I.1. Hosts and Groups

Inventory file can use many formats.
ini:
mail.example.com

[webservers]
foo.example.com
bar.example.com

[dbservers]
one.example.com
two.example.com
three.example.com
yaml:
all:
  hosts:
    mail.example.com
  children:
    webservers:
      hosts:
        foo.example.com:
        bar.example.com:
    dbservers:
      hosts:
      one.example.com:
      two.example.com:
      three.example.com:

If you have hosts that run on non-standard SSH ports you can put the port number after the hostname with a colon.

badwolf.example.com:5309

Setup alias for host jumper:

jumper ansible_port=5555 ansible_host=192.0.2.50
Using pattern:
[webservers]
www[01:50].example.com

[databases]
db-[a:f].example.com

I.1.2 Groups and groups variables.

we can group some hosts --> groups we can group some groups --> groups of groups we can declare variables for groups using: [group_name:vars]

[southeast:vars]
some_server=foo.southeast.example.com
halon_system_timeout=30
self_destruct_countdown=60
escape_pods=2

There is 2 default groups:

  • all: every host
  • ungrouped: all hosts in all group and not in any other group.

I.3. Dynamic Inventory:

  • write a script to get host - named external inventory script.
  • using -i to that file
  • ansible will apply for hosts collected.

For example, AWS EC2 external inventory script:

  • write script
  • using -i or copy that script to /etc/ansible/hosts and chmod +x it

Using inventory directories and multiple inventory sources

  • if location given to -i is a directory, ansible can use mutiple inventory sources at the same time.
  • it is possible to mix both of dynamic and static inventory.

Static Groups of Dynamic Groups

When defining groups of groups in static inventory files, the children group must be defined in static inventory file. If we want to define a static groups of dynamic children groups, define dynamic children group as an empty in inventory file

[tag_Name_staging_foo]

[tag_Name_staging_bar]

[staging:children]
tag_Name_staging_foo
tag_Name_staging_bar

Patterns

Pattern in ansible is HOW WE DECIDE which HOST to MANAGE.

ansible <pattern_goes_here> -m <module_name> -a <arguments>

*, all: all hosts

192.0.2.*

A:B: host in groups A OR B

webservers
webservers:dbservers

!: exclude

webservers:!phoenix

A:&B: host in group A AND B

webservers:&phoenix

We can mix above types of parterns to use,

You can select a host or subset of hosts from a group by their position. For example, given the following group:

[webservers]
cobweb
webbing
weber

You can refer to hosts within the group by adding a subscript to the group name:

webservers[0] # == cobweb
webservers[-1] # == weber
webservers[0:1] # == webservers[0],webservers[1]
webservers[1:] # == webbing,weber

Using partern as regex, start partern with ~

Ad-hoc command

Ad-hoc command is something that you type to use quickly and dont want to save for later.

$ ansible atlanta -a "/sbin/reboot" -f 10

-f: 10 simultaneous processes limited. Default is 5.

Gathering Facts

Facts is a section of playbook and represent discovered variables about a system.

see all facts:

$ ansible all -m setup

to disable gathering facts and shorten the running time of playbook:

garthering_facts: no

Networking support

= 2.1, ansible provides some modules to manage networking devices.

Playbook

Playbook is Ansible's configuration, deployment and orchestration. it configure all steps of process to manage your hosts as manage configuration and deployment.

Hosts and User

- hosts: webservers
  remote_user: root

hosts: choose remote hosts, groups. separated by colons :. remote_user: user to rung playbook on remote hosts

Using become to use other privilege

---
- hosts: webservers
  remote_user: yourname

tasks:
  - service:
    name: nginx
    state: started
    become: yes
    become_method: sudo

shell and command are special modules which just take a list of arguments and don't use key=varlue

tasks:
- name: run this command and ignore the result
  shell: /usr/bin/somecommand
  ignore_errors: True

Handlers

Running operation on changes

notify section of task triggers handlers.

- name: template configuration file
  template:
    src: template.j2
    dest: /etc/foo.conf
    notify:
      - restart memcached

Creating reusable playbook

Import and include

Import and include is quite similar, however ansible executor treated them very different:

  • import*: all statements will be proceessed before ansible playbooks are parsed
  • Include: statements will be processed during the execution of playbook

ansible >= 2.4, only include* is available

we can also declare variables when using include/import:

tasks:
- import_tasks: wordpress.yml wp_user=timmy
- import_tasks: wordpress.yml wp_user=alice
- import_tasks: wordpress.yml wp_user=bob

or using vars structure:

tasks:
- include_tasks: wordpress.yml
  vars:
    wp_user: timmy
    ssh_keys:
      - "{{ lookup('file', 'keys/one.pub') }}"

include and import also can be used in handlers section.

Role

we can include role in a task:

tasks:
- debug:
  msg: "before we run our role"
- import_role:
  name: example

Role can accept parameters:

- hosts: webservers
roles:
  - common
  - { role: foo_app_instance, dir: '/opt/a', app_port: 5000 }
  - { role: foo_app_instance, dir: '/opt/b', app_port: 5001 }

Role duplication

Add allow_duplicates: true to the meta/main.yml file for the role.

Role dependences:

in mete/main.yml file of role:

---
dependencies:
- { role: common, some_parameter: 3 }
- { role: apache, apache_port: 80 }
- { role: postgres, dbname: blarg, other_parameter: 12 }

Role search path

Ansible search roles in

  • role directory, relative with playbook files
  • in /etc/ansible/roles

Ansible variables

  • Variables can be used multiple time.
  • There is differences between systems, variables help us deal with this.

Variable can be defined in Inventory, playbook, include file or roles.

Using vars structure.

Using variables

Using jinja2 template

Registered variables

We can use shell/command module to run a command then registering result to a variable and using later.

- hosts: web_servers

  tasks:

     - shell: /usr/bin/foo
       register: foo_result
       ignore_errors: True

Register variables are valid on the host the remainder of playbook run

Playbook conditional

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment