Sie sind auf Seite 1von 67

Automate the System Operation with

Ansible
Getting Started
Overview

 Introduction to Ansible
 Advantages of using Ansible
 How does Ansible work?
 Installation Guide
Introduction to Ansible
• Ansible is a radically simple IT automation platform that makes your applications and systems
easier to deploy.

• It support configuration management with examples as below:


o Configuration of servers
o Application deployment
o Continuous testing of already install application
o Provisioning
o Orchestration
o Automation of tasks
Advantages of Ansible
• Free. Ansible is an open-source tool.

• Very simple to set up and use. No special coding skills are necessary to use Ansible’s
playbooks (more on playbooks later).

• Powerful. Ansible lets you model even highly complex IT workflows.

• Flexible. You can orchestrate the entire application environment no matter where it’s
deployed. You can also customize it based on your needs.

• Agentless. You don’t need to install any other software or firewall ports on the client systems
you want to automate. You also don’t have to set up a separate management structure.

• Efficient. Because you don’t need to install any extra software, there’s more room for
application resources on your server.
How does Ansible work?

A basic Ansible command or playbook:


• Selects machines to execute against from inventory
• connects to those machines (or network devices, or other managed
nodes), usually over SSH
• copies one or more modules to the remote machines and starts
execution there
How does Ansible work?
How does Ansible work?
Installation Guide
Requirement:
• CentOS or Ubuntu (We using CentOS 7 Minimal in this Course)
• Internet is required for installing dependencies

Installtion Step:
• Install Epel repository on your system:
sudo yum -y install epel-release
• Install Ansible:
sudo yum -y install ansible
Review

 Introduction to Ansible
 Advantages of using Ansible
 How does Ansible work?
 Installation Guide
Working with command line tools
Overview

 List of Ansible Command Line/Utilities


 Ansible and Ansible-playbook command
List of Ansible Command Line/Utilies
Command Description

ansible** Run single task against set of hosts

ansible-playbook** Run Ansible playbook (multi tasks) against set of hosts

ansible-config View ansible configs

ansible-console* Running Ansible in console mode and execute command in remote hosts

ansible-doc Displays information on modules installed in Ansible libraries.

ansible-galaxy Command to manage Ansible roles in shared repositories, the default of


which is Ansible Galaxy https://galaxy.ansible.com
ansible-inventory Used to display or dump the configured inventory as Ansible sees it

ansible-pull Used to up a remote copy of ansible on each managed node

ansible-vault* Encrypt any structured data file used by Ansible: group_vars, host_vars,
Inventory variables...
Ansible and Ansible-playbook command

ansible ansible-playbook
• Execute Automate task on remote hosts via • Execute Automate tasks on remote hosts via
command (single tasks). pre-defined playbook (multiple tasks)
• Known as Ad-hoc Command • Example:
• Example:
Review
 List of Ansible Command Line/Utilities
 Ansible and Ansible-playbook command
Introduction in Ad-hoc Commands
Overview

 What is an ad-hoc command in Ansible?


 Use cases for ad-hoc commands
 Ad-hoc vs Playbook
 Ansible command syntax
 Common modules
What is an ad-hoc command in Ansible?

• You can run ansible either ad-hoc or as a playbook


• Bother methods have the same capabilites
• Ad-hoc commands are effectively one-lines
[root@demo ansible]# ansible all -a "free -h" -k
SSH password:
VM01 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7.5G 2.1G 2.5G 74M 3.0G 5.1G
Swap: 2.0G 0B 2.0G

VM02 | CHANGED | rc=0 >>


total used free shared buff/cache available
Mem: 7.5G 1.3G 3.6G 74M 2.6G 5.9G
Swap: 2.0G 0B 2.0G
Use cases for Ad-hoc commands
• Operational commands
o Checking log contents
o Daemon control
o Process management
• Information commands
o Check installed software
o Check system propertes
o Gather system performance information (CPU, disks space, memory use)
• Research
• Work with unfamiliar modules on test systems
• Practice for playbook engineering
Ad-hoc vs Playbook

Ad-hoc mode Playbook Mode

Command: ansible Command: ansible-playbook

Effective for one-time commands, operational Effective for deployments, routine tasks, system
activities, information gathering and research deployment

Similar to a single bash command Similar to bash script


Ansible command syntax
[root@demo ansible]# ansible all -m yum -a "name=iptables,iptables-services state=latest" -k
SSH password:
VM01 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [],
"updated": []
},
"msg": "",
"rc": 0,
"results": [
"All packages providing iptables are up to date",
"All packages providing iptables-services are up to date",
""
]
}
Review
 What is an ad-hoc command in Ansible?
 Use cases for ad-hoc commands
 Ad-hoc vs Playbook
 Ansible command syntax
 Common modules
Working With Inventory
Overview

 Use both static and dynamic inventories to define group of hosts:


 What is the inventory
 File formats
 Static vs Dynamic
 Utilize an existing dynamic inventory script:
 On dynamic inventories
 Some Popular options
What is an Inventory?
• An inventory is a list of hosts that Ansible manages
• Inventory location may be specified as follows:
o Default: /etc/ansible/hosts
o Specified CLI: ansible -i <file_name>
o Can be set in ansible.cfg
• The inventory file may contain hosts, patterns, groups and variables
• You may specific the inventory as a directory containing a series of inventory files (both static
and dynamic)
• The inventory may be specified in YAML or INI format
• Can be static or dynamic
File Formats

YAML

INI
Static vs Dynamic

Static Dynamic

INI or YAML format Executable (bash script, python script, etc)

Script return JSON containing inventory


Maintained by hand
information

Good to use with cloud resources subject to


Easy to manage for static configuration
sudden change
Variables and Inventories
• Ansible recommend that variables not be defined in inventory files:
• Should be stored in YAML files located relative to inventory file
• group_vars
• host_vars
• Files named by host or group and may end in yml or yaml
On Dynamic Inventories

• Specifying an executable file as the • The program script must return JSON in the
inventory is considered a dynamic inventory format Ansible expecting
• JSON ouput is expected to be return to • Do not forget to make the file executable:
STDOUT from the executable o chmod +x dynamic.py
• The implementation (python, java, C, bash, • Using dynamic inventories, you can pull
etc) does not matter as long as the program inventory information from like of:
can run on the control host and behaves as o A cloud provider
Ansible expects o LDAP
• The program/script must respond to two o Cobbler
possible parameters: o Other CMDB Software
o --list
o --host [hostname]
Some Popular Options

• Cobbler
• AWS EC2
• VMware
• Openstack
• Plenty of documentation available
Review
 Use both static and dynamic inventories to define group of hosts:
 What is the inventory
 File formats
 Static vs Dynamic
 Utilize an existing dynamic inventory script:
 On dynamic inventories
 Some Popular options
Working With Modules
Overview

 Introduction to modules
 Return values
 Common modules
Introduction to Modules
• Ansible ships with a number of modules (called the 'module library') that can be
executed directly on remote hosts or through Playbooks.
• User can write their own modules. These modules can control system resources, like
service, packages, files or handle executing system commands.
• Modules index:
https://docs.ansible.com/ansible/latest/modules/modules_by_categ
ory.html
Return values
• Ansible modules normally return a data structure
that can be registered into a variable, or seen
directly when output by the ansible program.

• Each module can have its own unique return


values (visible through ansible-doc and on the
main docsite).

• User can using return value for defining workflow


by using Conditionals **
Common Modules
Ping Setup Yum
Validate server is up and Gather ansible facts Use Yum package manager
reachable
No requirement parameters No requirement parameters name

Service User Copy


Control Daemon Manipulate system users Copy files

name name src and dest

File Git
Work with files Interac with git repositories

path repo and dest


Review
 Introduction to modules
 Return values
 Common modules
Working With Playbook
Overview

 Know how to work with commonly used Ansible modules


 Create playbooks to configure system to specified state
 Use variables to retrive the results of running commands
 Use conditional to control play execution
 Configure error handling
 Selective runs specified tasks in playbooks using tags
Know how to work with Commonly Used Ansible Modules
• Core modules to be familiar with:
• Working with files: copy, archive, unarchive, get_url
• user, group
• ping
• service
• yum
• Lineinfile module
• htpasswd
• Shell and command modules
See more
• Script module https://docs.ansible.com/ansible/latest/modules/modules_by_
category.html
• Debug module
Create Playbooks to Configure Systems to a Specified State
---
• Reviewing plays and playbooks: - hosts: webserver
remote_user: root
o Plays map a group of hosts to well-
tasks:
defined roles - name: Ensure apache is at the latest version
yum: name=httpd state=latest
o Playbook are used to orchestrate - name: Write the apache config file
template: src=/srv/httpd.j2. dest=/etc/httpd.conf
more complex activities, such as
- hosts: databases
system or application deployment remote_user: root
tasks:
• Brush up on yaml - name: ensure postgresql is at the latest version
yum:
• Basic Syntax name: postgresql
state: latest
• Pro tips: Retry, Limit, Watch out for - name: ensure that postgresql is started
service:
spaces
name: postgresql
state: started
Use Variables to Retrieve the Result of Running Commands
• The register keyword
• May be referenced with the play
• Many attributes returned
- hosts: webserver
tasks:
- name: Copy file to remote servers
copy:
src: ./test_file
dest: /tmp/file123
mode: 0775
owner: root
group: root
register: demo_var

- name: Output debug info


debug:
msg: "Debug infor is {{ demo_var }}"
Use Conditionals to Control Play Execution
- name: template configuration file handlers:
template: - name: restart apache
src: template.j2
service:
dest: /etc/foo.conf
name: httpd
notify:
state: restarted
- roll web
listen: “roll web”

# If there is a meta module between 2 tasks, what will happen?


- meta: flush_handlers

- name: Stop apache service


service:
name: httpd
state: stopped
Use Conditionals to Control Play Execution

• When ---

• With_items - hosts: all


tasks:
• With_files
- name: copy file
copy:
src: "{{ item }}"
dest: "/home/user/{{ item }}"
mode: 775
with_items:
- file1
- file2
Configure Error Handling
• Ignoring acceptable errors
• Defining failure conditions
• Defining "Changed"
• Blocks

See more
https://docs.ansible.com/ansible/latest/user_guide/playbooks_error_handling.html
Selective Run Specified Tasks inn Playbooks Using Tags
If you have a large playbook, it may become useful to be able to run only a specific part of it
rather than running everything in the playbook

ansible-playbook –i inventory/inventory test.yml --tags packages

or

ansible-playbook –i inventory/inventory test.yml --skip-tags configuration

See more
https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html
Review
 Know how to work with commonly used Ansible modules
 Create playbooks to configure system to specified state
 Use variables to retrive the results of running commands
 Use conditional to control play execution
 Configure error handling
 Selective runs specified tasks in playbooks using tags
Working With Patterns
Overview

 Understaning Pattern in Ansible


 How to use?
 Common Patterns
Understanding Patterns in Ansible
• Choose which managed Hosts or Groups you want to execute Against instead or running all
Hosts from static/dynamic Inventory.
• Ansible Pattern can refer to a single host, an IP Address, an Inventory Group, a Set of Groups,
or all Hosts
• You can use Pattern either Ad-hoc or as a playbook.
How to use?
Ad-hoc Playbook

- Define Host(s)/Group(s) Patterns in - Define Host(s)/Group(s) Patterns in Command or


command Playbook
- Command: By adding agurment –limit

- In Playbook

- Using all or * to execute all Hosts in - Using all or * to execute all Hosts in inventory
inventory
Common Patterns

Description Pattern(s) Targets

All hosts all or (*)

One host host1

Multiple hosts host1:host2 or host1,host2

One Groups webservers

All hosts in webservers plus all hosts in


Multi Groups webservers:dbservers
dbservers
All hosts in webservers except those in
Excluding Groups webservers:!dbservers
dbservers
Any hosts in webservers that are also in
Intersection of Groups webserver:&staging
staging
Review
 Understaning Pattern in Ansible
 How to use?
 Common Patterns
Working With Ansible Vaults
Overview

 Understaning Ansible Vault


 What can be encrypted with Vault
 How to use?
Understanding Ansible vault
• Vault is a mechanism that allows encrypted content to be incorporated transparently into
Ansible workflows.
• Encrypt any structured data file used by Ansible for hiding information:
o Inventory variables: group_vars, host_vars
o Variables loaded by include_vars or vars_files
o Variable files passed on the ansible-playbook command line
o Role variables
• Ansible-vault is used to initially encrypt files and is subsequently used to view, edit, or decrypt
the data.
What can be Encrypted with Vault
Type Description

File-level encryption Ansible Vault can encrypt any structured data file used by Ansible.

Variable-level encryption Supports encrypting single values inside a YAML file, using
the !vault tag to let YAML and Ansible know it uses special processing
How to use?
• Encrypt inventory file
How to use?
• Run Ansible with Encrypted inventory file => ERROR
How to use?
• Run Ansible with Encrypted inventory file with --ask-vault-pass

• The playbook (date.yml) can be encrypted too


• More information: https://docs.ansible.com/ansible/latest/user_guide/vault.html
Overview

 Understaning Ansible Vault


 What can be encrypted with Vault
 How to use?
Other
Ansible‘s Directory Structure – Best Practice
Role’s Directory Structure (Ansible’s Subdirectory)
Junos Ansible Modules

Ansbile build-in modules Juniper JunOS Ansible modules


http://docs.ansible.com/ansible/latest/modules/lis http://junos-ansible-
Link t_of_network_modules.html#junos modules.readthedocs.io/en/2.0.1/
Reference

Number of
20 11
Modules
Ansbile build-in modules Juniper JunOS Ansible modules
junos_banner juniper_junos_command
junos_command juniper_junos_pmtud
junos_config juniper_junos_jsnapy
junos_facts juniper_junos_software
junos_interface juniper_junos_rpc
junos_l2_interface juniper_junos_facts
junos_l3_interface juniper_junos_system
junos_linkagg juniper_junos_config
junos_lldp juniper_junos_ping
junos_lldp_interface juniper_junos_table
junos_logging juniper_junos_srx_cluster
List Modules junos_netconf
junos_package
junos_rpc
junos_scp
junos_static_route
junos_system
junos_user
junos_vlan
junos_vrf
THANK YOU

Das könnte Ihnen auch gefallen