0% found this document useful (0 votes)
86 views67 pages

Ansible - Part1

This document provides an overview and agenda for an Ansible training session. It introduces Ansible as an open-source automation platform for configuration management, task automation, application deployment and IT orchestration. It outlines the learning objectives which include understanding what Ansible is, why it is used, key terminology, and how to install it. It also provides steps to set up an Ansible environment including launching EC2 instances from a bastion host, configuring SSH access between servers using SSH keys, and distributing the SSH keys.

Uploaded by

bala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views67 pages

Ansible - Part1

This document provides an overview and agenda for an Ansible training session. It introduces Ansible as an open-source automation platform for configuration management, task automation, application deployment and IT orchestration. It outlines the learning objectives which include understanding what Ansible is, why it is used, key terminology, and how to install it. It also provides steps to set up an Ansible environment including launching EC2 instances from a bastion host, configuring SSH access between servers using SSH keys, and distributing the SSH keys.

Uploaded by

bala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Ansible

Ansible
Agenda
Ansible
● Introduction Instructions / Notes
● Starts: 16 May, 7:30am PDT/PST or 16 May, 8pm IST
● Ansible pre-requiste
● 2 Hours session with 10 minutes Break
● Inventory Management
● Except Instructor, everyone is on mute
● Adhoc Command ● Please use the Q/A Window to Ask Questions
● Playbook ● The recording & slides will be shared after session

● Configuration Management ● More Info: CloudxLab.com

● Roles
● Ansible Vault
● Build K8 Cluster using Ansible
Ashok Singh
Ansible
Introduction

Ansible
Learning Objective
● What is ansible?

● Why do we use ansible?

● Ansible terminologies

● Ansible Installation

Ansible
What is ansible?

● Open Source Automation platform

● Simple , Efficient and Powerful

Configuration Task Automation Application IT


Management Deployment Orchestration

Ansible
Why do we use ansible?
● Ansible is open source

● Ansible is agentless

● Ansible uses SSH

● Minimal system requirement

● Lightweight and fast deployment

● Developed in Python

● Ansible uses Yaml syntax

● Large community

Ansible
Ansible Terminologies
● PLAYBOOKS

● TASK

● ACTION

● FACTS

● HOSTS

● GROUPS

● HANDLERS

● AD-HOC
Ansible
Ansible Terminologies
● INVENTORY ● ROLES

● MODULES ● TEMPLATES

● LIBRARY ● WHEN

● NOTIFY ● YAML

● ORCHESTRATION

● PUSHMODE

● PULLMODE

Ansible
Ansible Installation

Using Apt
• apt-get install ansible

Using Yum
• yum install ansible

Ansible
Lab01: Launch new EC2 from bastion
Task: Prepare host and validate it by launching playbook that will create a new
ec2 instance
Step1 : Launch EC2 instance . Tag it as bastion and connect to bastion host
ashoksingh@Ashoks-Air ~/ ssh -i aws-key.pem ec2-user@<PUBLIC_IP>
The authenticity of host '3.8.176.4 (3.8.176.4)' can't be established.
ECDSA key fingerprint is SHA256:qLP4m9hCsRZc2Nnz1kWn0PgjdLay4GyZmzxz+RggHfY.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '3.8.176.4' (ECDSA) to the list of known hosts.

__| __|_ )
_| ( / Amazon Linux 2 AMI
___|\___|___|

https://aws.amazon.com/amazon-linux-2/
[ec2-user@ip-172-31-20-142 ~]$

Ansible
Lab01: Launch new EC2 from bastion

Step2 : Become root

[ec2-user@ip-172-31-24-224 ~]$ sudo su -


[root@ip-172-31-24-224 ~]#

Step3 : Install git and clone repo


[root@ip-172-31-24-224 ~]# yum install -y git
[root@ip-172-31-24-224 ~]# git clone
https://github.com/singh-ashok25/aws-ansible.git

Step4 : Install python3 and ansible


[root@ip-172-31-24-224 ~]# cd aws-ansible
[root@ip-172-31-24-224 ~]# ./packages.sh

Ansible
Lab01: Launch new EC2 from bastion
Step5 : Create virtual environment for python3
[root@ip-172-31-24-224 aws-ansible]# python3 -m venv ansible
[root@ip-172-31-24-224 aws-ansible]# source /root/aws-ansible/ansible/bin/activate
(ansible) [root@ip-172-31-24-224 aws-ansible]# pip install pip --upgrade

Step6 : Install boto library for aws module


(ansible) [root@ip-172-31-24-224 aws-ansible]# pip install boto
Collecting boto
Downloading boto-2.49.0-py2.py3-none-any.whl (1.4 MB)
|████████████████████████████████| 1.4 MB 11.3 MB/s
Installing collected packages: boto
Successfully installed boto-2.49.0
(ansible) [root@ip-172-31-24-224 aws-ansible]#

Ansible
Lab01: Launch new EC2 from bastion
Step7 : Configure aws credentials
(ansible) [root@ip-172-31-24-224 aws-ansible]# aws configure
AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXXXXXXX
AWS Secret Access Key [None]: XXXXXXXXXXXXXXXXXXXXXXXXX
Default region name [None]: eu-west-2
Default output format [None]: json

Step8 : Configure playbook variable ec2.yml


keypair: aws-key
instance_type: t2.micro
security_group: default
image: ami-01a6e31ac994bbc09
region: eu-west-2
subnet: subnet-082213e51ccfdcaa4

Ansible
Lab01: Launch new EC2 from bastion
Step9 : Key-pair is the ssh key used to connect to ec2-instance.

image: ami-01a6e31ac994bbc09

subnet: subnet-082213e51ccfdcaa4

Ansible
Lab01: Launch new EC2 from bastion
Step10 : Run the ansible playbook
(ansible) [root@ip-172-31-24-224 aws-ansible]# ansible-playbook -i
inventory ec2.yml

PLAY [Create a sandbox instance] ***************************************

TASK [Launch instance] *************************************************


changed: [localhost]

PLAY RECAP *************************************************************


localhost : ok=1 changed=1 unreachable=0
failed=0 skipped=0 rescued=0 ignored=0
(ansible) [root@ip-172-31-24-224 aws-ansible]#

Ansible
Lab01: Launch new EC2 from bastion
Step11 : Validate new ec2 is created in AWS console.

Ansible
Set up SSH access between servers

Ansible
ssh keys based access
Ansible works on assumption that all server can be accessed by ansible
host using ssh key

Server1

Bastion Server2

Server3

Ansible
SSH Key distribution

s3 bucket

pem

aws
- key.
s
aw Server1

-ke
y.pe
u b
s a.p

m
aws-key.pem - r
id

Bastion Server2
Laptop id-rsa.pub

id-
ssh key pair rsa
.pu
id-rsa.pem b
id-rsa.pub
Server3

AWS

Ansible
SSH Key distribution
Step 1: Login to bastion host and update ec2.yaml file to launch 3 ec2 instances

...
- name: Launch instance
ec2:
count: 3
...

Step2: Run the playbook


(ansible) [root@ip-172-31-24-224 aws-ansible]# ansible-playbook -i
inventory ec2.yml
...
PLAY RECAP *******************************************************”*”**
localhost : ok=1 changed=1 unreachable=0
failed=0 skipped=0 rescued=0 ignored=0

Ansible
Launch 3 instances
Step 1: Login to bastion host and update ec2.yaml file to launch 3 ec2 instances

...
- name: Launch instance
ec2:
count: 3
...

Step2: Run the playbook


(ansible) [root@ip-172-31-24-224 aws-ansible]# ansible-playbook -i
inventory ec2.yml
...
PLAY RECAP *******************************************************”*”**
localhost : ok=1 changed=1 unreachable=0
failed=0 skipped=0 rescued=0 ignored=0

Ansible
Method-1: pusk aws-key to s3 bucket and copy to bastion
● push private key to s3-bucket
ashoksingh@Ashoks-Air ~/ aws s3 mb s3://devops-bucket-new
make_bucket: devops-bucket-new
ashoksingh@Ashoks-Air ~/ aws s3 cp aws-key.pem s3://devops-bucket-new
upload: ./aws-key.pem to s3://devops-bucket-new/aws-key.pem
ashoksingh@Ashoks-Air ~/ aws s3 ls
2020-05-15 10:40:50 devops-bucket-new

● copy private key from s3 bucket to bastion and delete it


[root@ip-172-31-24-224 aws-ansible]# aws s3 cp
s3://devops-bucket-new/aws-key.pem .
download: s3://devops-bucket-new/aws-key.pem to ./aws-key.pem
[root@ip-172-31-24-224 aws-ansible]# chmod 400 aws-key.pem
[root@ip-172-31-24-224 aws-ansible]# aws s3 rb --force s3://devops-bucket-new

Ansible
Method-2: copy aws-key private key to bastion
● Copy private key

ashoksingh@Ashoks-Air ~/ cat aws-key.pem


-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEArbFlJ9OK6iiEUcBuhGLd5PG6ghdm9ojRu4KvzCLEXxzny7EPvhJsfpGCU1Jd
..
keazVZFF2hsPDATwHRPHgHEJmK46MIEytBhDh292M9TqMnFUCwkDsRZojarAdO5v2l1L
-----END RSA PRIVATE KEY-----%

Paste the key on bastion host


[root@ip-172-31-24-224 aws-ansible]# vi aws-key.pem
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEArbFlJ9OK6iiEUcBuhGLd5PG6ghdm9ojRu4KvzCLEXxzny7EPvhJsfpGCU1Jd
..
keazVZFF2hsPDATwHRPHgHEJmK46MIEytBhDh292M9TqMnFUCwkDsRZojarAdO5v2l1L
-----END RSA PRIVATE KEY-----%
[root@ip-172-31-24-224 aws-ansible]# chmod 400 aws-key.pem

Ansible
Test connectivity from bastion to server
● Connect to server1
[root@ip-172-31-24-224 aws-ansible]# ssh -i aws-key.pem ec2-user@3.8.157.226
(ansible) [root@ip-172-31-24-224 aws-ansible]# ssh -i aws-key.pem
ec2-user@3.8.157.226
The authenticity of host '3.8.157.226 (3.8.157.226)' can't be established.
...
[ec2-user@ip-172-31-39-247 ~]$

● Connect to server2
[root@ip-172-31-24-224 aws-ansible]# ssh -i aws-key.pem ec2-user@18.132.39.66
(ansible) [root@ip-172-31-24-224 aws-ansible]# ssh -i aws-key.pem
ec2-user@3.8.157.226
The authenticity of host '3.8.157.226 (3.8.157.226)' can't be established.
...
[ec2-user@ip-172-31-40-250 ~]$

Ansible
key pair
ssh is based on public and private key . recommended bit size 4096

1. id_rsa - private key


2. id_rsa.pub - public key Public Key Example
ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAACAQCaD0O37wnM9KU2gjnPWYFGzUtuyJ
c4C+S+hJDWI4C7duzCCgkWl2ehnLkkuekab2D/wV996F0eRw
Private Key Example nyMIdQGICdoWQtArhE5SRTDQ4fxflWkrtDenh0FtfpRFOar1RhQNa6DINIcURktu8f
q/3a4ffx6l9ggu15DLXIMDNwmnUgCf4a1F0Uhb3p27RRl4Nf
HPgvSQu292UKz/8LsLgdkQj7GTIOovztX6q2B4NcdJJ2XTV1PCLc3VaGPl40HlfBf
-----BEGIN RSA PRIVATE KEY-----
BKPO4wAxNsmbCTo3rdcQsdDOvFQPUAaL3ii6EsbJ2hIkFEPQE
MIIJKgIBAAKCAgEAmg9Dt+8JzPSlNoI5z1mBRs1LbsiXOAvkvoSQ1iOAu3bswgoJ
sUWisZK0TH5VudoFNu8ltKqln/xG53fkrHrobDJ0y9hGE8bGL1Etuv8owCd4hmR0
FpdnoZy5JLnpGm9g/8FffehdHkcJ8jCHUBiAnaFkLQK4ROUkUw0OH8X5VpK7Q3p4
WoNUwuVzMCDIZssiW0EKQhoqOLl8ISRASxY+Tw9j51CVUaQdHL
dBbX6URTmq9UYUDWugyDSHFEZLbvH6v92uH38epfYILteQy1yDAzcJp1IAn+GtRd
huvl8ee+8yUAaA95q106ekHXejdaMgRHBNpdji9OVPEC7fYTaMP+GJ/3Ac1xYksA
FIW96du0UZeDXxz4L0kLtvdlCs//C7C4HZEI+xkyDqL87V+qtgeDXHSSdl01dTwi
OhaWjAvKSx92QnVTGF4brbPHrgQJGQMOc9TcQVHGT5N2WLEzm+
3N1Whj5eNB5XwXwSjzuMAMTbJmwk6N63XELHQzrxUD1AGi94ouhLGydoSJBRD0BL
7fC3zXb+9JMQwOtmRw4yEDjgnejlIjZkvoJCevK0BF8eRPCVWM9Elb6PgM2TVJia
FForGStEx+VbnaBTbvJbSqpZ/8Rud35Kx66GwydMvYRhPGxi9RLbr/KMAneIZkdF
ZdUaDP6Jp2rnZ+eOBDl1QaNLdgksUg6NB1py7c8xutiNrikucI
qDVMLlczAgyGbLIltBCkIaKji5fCEkQEsWPk8PY+dQlVGkHRy4br5fHnvvMlAGgP
NX8nJm4S5n3poUZQ0pCKnft7/a3oGQQwGGSrxw==
root@ip-172-31-24-224.eu-west-2.compute.internal

Ansible
Generate ssh key pair
Step 3: Login to bastion host generate key pair
(ansible) [root@ip-172-31-24-224 aws-ansible]# ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:btj2YMEDuvHNa3K9x1OKm1L/FR0Fq+zyUy9Lz1gsISE
root@ip-172-31-24-224.eu-west-2.compute.internal
The key's randomart image is:
+---[RSA 4096]----+
..
..
+----[SHA256]-----+
(ansible) [root@ip-172-31-24-224 aws-ansible]# ls -l ~/.ssh/id*
-rw------- 1 root root 3247 May 15 01:27 /root/.ssh/id_rsa
-rw-r--r-- 1 root root 774 May 15 01:27 /root/.ssh/id_rsa.pub
(ansible) [root@ip-172-31-24-224 aws-ansible]#
Ansible
Copy new public key on servers
● copy public key to all server. Below is example of server1
(ansible) [root@ip-172-31-24-224 aws-ansible]#
cat ~/.ssh/id_rsa.pub | ssh -i aws-key.pem ec2-user@3.8.157.226 "cat >>
~/.ssh/authorized_keys"
(ansible) [root@ip-172-31-24-224 aws-ansible]# ssh ec2-user@172.31.39.247
Last login: Fri May 15 15:31:35 2020 from 3.8.125.192

__| __|_ )
_| ( / Amazon Linux 2 AMI
___|\___|___|

https://aws.amazon.com/amazon-linux-2/
1 package(s) needed for security, out of 10 available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-172-31-39-247 ~]$

Ansible
Copy new public key on servers
● copy public key to all server. Below is example of server1
(ansible) [root@ip-172-31-24-224 aws-ansible]#
cat ~/.ssh/id_rsa.pub | ssh -i aws-key.pem ec2-user@3.8.157.226 "cat >>
~/.ssh/authorized_keys"
(ansible) [root@ip-172-31-24-224 aws-ansible]# ssh ec2-user@3.8.157.226
Last login: Fri May 15 15:31:35 2020 from 3.8.125.192

__| __|_ )
_| ( / Amazon Linux 2 AMI
___|\___|___|

https://aws.amazon.com/amazon-linux-2/
1 package(s) needed for security, out of 10 available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-172-31-39-247 ~]$

Ansible
Copy new public key on servers
● copy public key server2 and server3
(ansible) [root@ip-172-31-24-224 aws-ansible]#
cat ~/.ssh/id_rsa.pub | ssh -i aws-key.pem ec2-user@<IP_SERVER2> "cat >>
~/.ssh/authorized_keys"
(ansible) [root@ip-172-31-24-224 aws-ansible]#
cat ~/.ssh/id_rsa.pub | ssh -i aws-key.pem ec2-user@<IP_SERVER3> "cat >>
~/.ssh/authorized_keys"

Ansible
Ansible ping test
Create a host file with list of IP address
(ansible) [root@ip-172-31-21-72 aws-ansible]# cat hosts
[servers]
172.31.44.11
172.31.40.165
172.31.41.94

[external]
35.176.249.69
3.9.178.160
3.8.28.212
(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible -m ping -i hosts
servers -u ec2-user

Ansible
Inventory Management

Ansible
What is Inventory ?
Ansible works against multiple managed nodes or "hosts" in your
infrastructure at the same time, using a list or group of lists known as
inventory
Source: Ansible.com

Ansible
Inventory file
● Default location and file is
○ /etc/ansible/hosts

● Custom inventory files can be specified command line with option “-i”
○ -i <path>

(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible -m ping -i hosts servers -u


ec2-user

Ansible
Inventory file format
● Host are grouped in heading in square bracket in INI format of indentation in YAML

all: mail.example.com
hosts:
mail.example.com: [webservers]
children: foo.example.com
webservers: bar.example.com
hosts:
foo.example.com: [dbservers]
bar.example.com: one.example.com
dbservers: two.example.com
hosts: three.example.com
one.example.com:
two.example.com:
three.example.com:
INI
YAML
Ansible
Host Ranges
[webservers]
www01.example.com
www02.example.com [webservers]
www[01:04].example.com
www03.example.com
www04.example.com

[dbservers]
db-a.example.com
[dbservers]
db-b.example.com db[a:c].example.com
db-c.example.com

Ansible
Host and Group Variables
● Assign a variable to a single host, then use it later in playbooks
[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909
[targets]
localhost ansible_connection=local
other1.example.com ansible_connection=ssh ansible_user=myuser

● If all hosts in a group share a variable value, you can apply that variable
to an entire group at once
[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com

Ansible
Inventory :Best Practise
Each host can be in more than one group. For example a production
appserver in a datacenter in Atlanta might be included in groups called
[prod] and [atlanta] and [appservers]. You can create groups that track:
● What - An application, stack or microservice. (For example, database
servers, web servers, etc).
● Where - A datacenter or region, to talk to local DNS, storage, etc. (For
example, east, west).
● When - The development stage, to avoid testing on production
resources. (For example, prod, test).

Ansible
What , where and when sample Inventory
all: west:
hosts: hosts:
mail.example.com: bar.example.com:
children: three.example.com:
webservers: prod:
hosts: children:
foo.example.com: east:
bar.example.com: test:
dbservers: children:
hosts: west:
one.example.com:
two.example.com:
three.example.com:
east:
hosts:
foo.example.com:
one.example.com:
two.example.com:
Ansible
Adhoc Command

Ansible
What is Adhoc Command ?
Ad-hoc commands are task which are not executed rarely , but on all
server. These are one liner command that is executed on specified hosts

Ansible
User Case 1: Executing shell command
● Install git on all group of host called servers

(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible -m shell -a "sudo yum


install git -y " -i host servers
172.31.41.94 | CHANGED | rc=0 >>
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Resolving Dependencies
--> Running transaction check
---> Package git.x86_64 0:2.23.3-1.amzn2.0.1 will be installed
..
..
libsecret.x86_64 0:0.18.5-2.amzn2.0.2
perl-Error.noarch 1:0.17020-2.amzn2
perl-Git.noarch 0:2.23.3-1.amzn2.0.1
perl-TermReadKey.x86_64 0:2.30-20.amzn2.0.2

Complete!

Ansible
User Case 2: Managing files
● Copy file from host to remove servers

(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible servers -m copy -a


"src=/etc/hosts dest=/tmp/hosts" -i host
172.31.41.94 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "27c253e93d8b3af8e28fc5626e7869a1cbdfc7ab",
"dest": "/tmp/hosts",
"gid": 1000,
"group": "ec2-user",
"md5sum": "ab72d38661b6117245a34461c9566626",
"mode": "0664",
"owner": "ec2-user",
"size": 126,
"src": "/home/ec2-user/.ansible/tmp/ansible-tmp-1589588441.91-234929479258099/source",
"state": "file",
"uid": 1000
}
Ansible
User Case 3: Managing packages
● To ensure a package is installed without updating it:
$ ansible servers -m yum -a "name=httpd state=present" -i host --become

● To ensure a specific version of a package is installed:


$ ansible servers -m yum -a "name=httpd-2.4.41-1.amzn2.0.1.x86_64
state=present" -i host --become

● To ensure a package is at the latest version:


$ ansible servers -m yum -a "name=httpd state=latest" -i host --become

● To ensure a package is not installed:


$ ansible servers -m yum -a "name=httpd state=absent" -i host ---become

Ansible
User Case 4: Managing users and groups
● create, manage, and remove user accounts on your managed nodes with
ad-hoc tasks:

$ ansible servers -m user -a "name=foo password=<crypted


password here>" -i host --become

$ ansible servers -m user -a "name=foo state=absent" -i host


--beomce

Ansible
User Case 5: Managing services
● Ensure a service is started on all servers:
$ ansible servers -m service -a "name=httpd state=started" -i host
--become

● Alternatively, restart a service on all servers:


$ ansible servers -m service -a "name=httpd state=restarted"
-i host --become

● Ensure a service is stopped:


$ ansible servers -m service -a "name=httpd state=stopped" -i
host --become

Ansible
User Case 6: Gathering facts
Facts are discovered variables on remote host . They are uses to implement
conditional execution of tasks but also to get information about your systems.

$ ansible servers -m setup -i host

Ansible
Playbook

Ansible
What is Playbook ?
● Playbooks are Ansible's configuration, deployment, and
orchestration language.

● Playbooks offer a repeatable, re-usable, simple configuration


management and multi-machine deployment system,

● Playbook is composed of one or more 'plays' in an ordered


list.Each play executes part of the overall goal of the playbook,
running one or more tasks.
Ansible
Playbook Execution
● Task executes in order they are written in playbook

● Desired state and 'idempotency'


○ Changes to the remote host are not made is desired state is already
acheived

● Running playbooks
○ ansible-playbook playbook.yml -f 10

Ansible
Playbook - ec2.yml
---
- name: Create a sandbox instance
hosts: localhost
gather_facts: False
vars:
keypair: aws-key
instance_type: t2.micro
security_group: default
image: ami-09e5afc68eed60ef4
region: eu-west-2
subnet: subnet-082213e51ccfdcaa4

Ansible
Playbook - ec2.yml
tasks:
- name: Launch instance
ec2:
key_name: "{{ keypair }}"
group: "{{ security_group }}"
instance_type: "{{ instance_type }}"
image: "{{ image }}"
wait: true
region: "{{ region }}"
vpc_subnet_id: "{{ subnet }}"
assign_public_ip: yes
register: ec2

Ansible
Ansible module parameter (help?)

In order to get ansible module list


ansible-doc -l

parameter allowed in any module or name of module

ansible-doc <module-name>
ansible-doc yum

Ansible
Lab02: Create a playbook to deploy flaskapp
TASK:1 - Write a task to deploy Deploy docker. Copy below content in
flaskapp.yml file
---
- hosts: centos
become: true
tasks:
- name: Install docker
yum: name=docker state=latest

TASK:2- Run the playbook syntax checker


● ansible-playbook flask-app.yml --syntax-check

Ansible
Lab02: Create a playbook to deploy flaskapp
TASK:3- Run the playbook to deploy docker on remote host - centos
(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible-playbook flask-app.yml -i host

PLAY [centos] ********************************


TASK [Gathering Facts] *****************************
ok: [172.31.35.243]

TASK [Install docker]


*************************************************
changed: [172.31.35.243]

PLAY RECAP
***********************************************************
172.31.35.243 : ok=2 changed=1 unreachable=0
failed=0 skipped=0 rescued=0 ignored=0

Ansible
Lab02: Create a playbook to deploy flaskapp
TASK:4- Add Task to start docker service
- name: Start docker service
service: name=docker state=started

TASK:5- Add Task run flaskapp docker container on host

name: Start flask app on port 80


shell:
cmd: docker run -dit -p 80:4080 ashok25/flaskapp:v2.0

Ansible
Lab02: Create a playbook to deploy flaskapp
TASK:7- Run the playbook
(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible-playbook flask-app.yml -i host

PLAY [centos] ********************************


TASK [Gathering Facts] *****************************
ok: [172.31.35.243]
TASK:6- Add Task
TASK [Install run flaskapp
docker] docker container on host
*************************************************
changed: [172.31.35.243]
TASK [Start docker service] ********************************
ok: [172.31.35.243]
TASK [Start flask app on port 80]
***********************************
changed: [172.31.35.243]
PLAY RECAP ***********************************************************
172.31.35.243 : ok=2 changed=1 unreachable=0
failed=0 skipped=0 rescued=0 ignored=0

Ansible
Lab02: Create a playbook to deploy flaskapp
TASK:7- Access the flaskapp url
http://www.<public-url>:80

Ansible
Verifying playbook
● playbooks validation can be done with option --check, --diff, --list-hosts,
--list-tasks and --syntax-check

(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible-playbook


flask-app.yml -i host --check

PLAY [centos] ********************************************************

TASK [Gathering Facts] ***********************************************


ok: [172.31.35.243]
...
PLAY RECAP ************************************************************
172.31.35.243 : ok=3 changed=0 unreachable=0 failed=0
skipped=2 rescued=0 ignored=0

(
Ansible
List hosts in playbook
● List all the host which are impacted in playbook

(ansible) [root@ip-172-31-21-72 aws-ansible]#


ansible-playbook -i host flask-app.yml --list-hosts

playbook: flask-app.yml

play #1 (centos): centos TAGS: []


pattern: [u'centos']
hosts (1):
172.31.35.243
(ansible) [root@ip-172-31-21-72 aws-ansible]#

Ansible
List tasks in playbook
● List all the tasks from

(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible-playbook


flask-app.yml -i host --list-tasks

playbook: flask-app.yml

play #1 (centos): centos TAGS: []


tasks:
Install docker TAGS: []
Start docker service TAGS: []
Start flask app on port 80 TAGS: []
Stop flask app on port 80 TAGS: []
(ansible) [root@ip-172-31-21-72 aws-ansible]#

Ansible
Handlers- playbook
● Handlers are tasks that only run
when notified.

● Each handler should have a


globally unique name.

● handlers run after all the tasks in a


particular play have been
completed

Ansible
Configuration management

Ansible
Ansible Configuration file
● Configuration file define # config file for ansible -- https://ansible.com/
# ===============================================
location of other input file
or default parameter # nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
● Default file location
[defaults]
/etc/ansible/ansible.cfg
# some basic default values...

inventory = new-hosts
#library = /usr/share/my_modules/
#module_utils = /usr/share/my_module_utils/

Ansible
Override inventory file
● Check which configuration is used by ansible
(ansible) [root@ip-172-31-21-72 aws-ansible]# ansible -v -m shell -a "ls" all
Using /etc/ansible/ansible.cfg as config file
172.31.35.243 | CHANGED | rc=0 >>

● Check which host file is used by ansible


(ansible) [root@ip-172-31-21-72 aws-ansible]# grep inventory
/etc/ansible/ansible.cfg | grep =
#inventory = /etc/ansible/hosts
(ansible) [root@ip-172-31-21-72 aws-ansible]# cat /etc/ansible/hosts
[centos]
172.31.35.243
(ansible) [root@ip-172-31-21-72 aws-ansible]#

Ansible
Override inventory file
● Create configuration in local directory and specify path for inventory file

(ansible) [root@ip-172-31-21-72 aws-ansible]# cp


/etc/ansible/ansible.cfg ansible.cfg

● Update local configuration file to use “new-hosts” inventory file


[defaults]
# some basic default values...
inventory = new-hosts
#library = /usr/share/my_modules/

Ansible
create a new inventory file
● copy default host file to local directory and edit it to point to wrong ip address
(ansible) [root@ip-172-31-21-72 aws-ansible]# cp /etc/ansible/hosts new-hosts
(ansible) [root@ip-172-31-21-72 aws-ansible]# echo 172.22.22.22 >> new-hosts

● Run ping test on ansible host

Ansible
Configuration Management
● Different hosts need different type of configuration parameter
● Organise configuration file and inventory file in different directory structure

(ansible) [root@ip-172-31-21-72 aws-ansible]# tree cm-dir/


cm-dir/
├── appserver
│ ├── ansible.cfg
│ └── inventory
├── dbserver
│ ├── ansible.cfg
│ └── inventory
└── webserver
├── ansible.cfg
└── inventory

Ansible

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy