Category Archives: Ansible

Learn Ansible with DevOpsRoles.com. Access detailed guides and tutorials to automate IT tasks and manage configurations efficiently using Ansible for DevOps.

Ansible get IP address remote server

#Introduction

In this tutorial, How to use Ansible get IP address remote server. There are many methods to obtain the IP address the current of remote hosts. so let us learn how to use Ansible to get an IP address to remote hosts’ servers.

Structure file and folder Ansible get IP address remote server

[vagrant@ansible_controller ~]$ pwd
/home/vagrant
[vagrant@ansible_controller ~]$ tree .
.
├── ansible
│   ├── ansible.cfg
│   └── hosts
└── getIP.yml

1 directory, 3 files

Option 1: use hostvars

To retrieve the IP address of a remote server using Ansible, you can use the ansible_default_ipv4 variable. This variable provides information about the default IPv4 address of the target host.

For example the content file getIP.yml as below

[vagrant@ansible_controller ~]$ cat getIP.yml
---
- hosts: servers
  tasks:
  - name: Test hosts list
    debug:
      msg: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"

The output on terminal

[vagrant@ansible_controller ~]$ ansible-playbook getIP.yml -i .ansible/hosts

PLAY [servers] *********************************************************************************************************

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

TASK [Test hosts list] *************************************************************************************************
ok: [server1] => {
    "msg": "10.0.2.15"
}

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

Here’s an example of how you can access the IP address:

Option 2: Other

For example the content file getIP.yml as below

[vagrant@ansible_controller ~]$ cat getIP.yml
---
- hosts: servers
  gather_facts: yes
  tasks:
  - name: Get IP address remote server
    debug:
      msg: "{{ hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2] }}"

The output on terminal

[vagrant@ansible_controller ~]$ ansible-playbook getIP.yml -i .ansible/hosts

PLAY [servers] *************************************************************************************************************

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

TASK [Get IP address remote server] ************************************************************************************
ok: [server1] => {
    "msg": "192.168.3.11"
}

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

Option 3: lookup and dig

For example the content file getIP.yml as below

[vagrant@ansible_controller ~]$ cat getIP.yml
---
- hosts: servers
  tasks:
  - name: Test hosts list
    debug:
      msg: "{{ lookup('dig', ansible_host) }}"

Make sure you have proper SSH access to the remote server and the necessary permissions to gather facts from it.

Conclusion

You have to use Ansible get IP address remote server. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Vagrant create ansible

Vagrant is a Configuration management tool. In this tutorial, I will use Vagrant to create an Ansible practice environment. Quickstart Vagrant create ansible your environment developer.

Vagrant create ansible

Install the plugin for Vagrant

$ vagrant plugin install vagrant-hosts
$ vagrant plugin install vagrant-host-shell
$ vagrant plugin install vagrant-vbguest
$ vagrant plugin list
  • vagrant-hosts: Enable name resolution between guests
  • vagrant-host-shell: Make the host’s shell command executable in Vagrantfile
  • vagrant-vbguest: For shared folder (automatic installation of VirtualBox Guest Additions on the guest)

Working folder for Ansible

$ mkdir -p vagrant-ansible/ansible
$ cd vagrant-ansible
$ vagrant init -m centos/7

Note: I will use vagrant init -m to create a simple Vagrantfile

Vagrantfile

I will create an Ansible controller and servers.

Vagrant.configure("2") do |config|

  config.vm.define :ansible_controller do |ansible_controller|
    ansible_controller.vm.box = "centos/7"
    ENV["LC_ALL"] = "en_US.UTF-8"
    config.ssh.insert_key = false
	ansible_controller.vm.synced_folder "./ansible", "/home/vagrant/ansible", type: "rsync"
    ansible_controller.vm.network "private_network", ip: "192.168.3.10", :netmask => "255.255.255.0"
    ansible_controller.vm.provision :hosts, :sync_hosts => true
    ansible_controller.vm.provision :host_shell do |host_shell|
      host_shell.inline = 'scp -i ~/.vagrant.d/insecure_private_key -o "StrictHostKeyChecking no" ~/.vagrant.d/insecure_private_key vagrant@192.168.3.10:/home/vagrant/.ssh/id_rsa'
    end
    ansible_controller.vm.provision "shell", inline: <<-SHELL
      chmod 600 /home/vagrant/.ssh/id_rsa
      timedatectl set-timezone asia/ho_chi_minh
      yum install -y epel-release
      yum -y update
      yum -y install python36 python36-libs python36-devel
      python36 -m ensurepip
      /usr/bin/pip3 install --upgrade pip
      /usr/bin/pip3 install ansible
      SHELL
  end

  N=2
  (1..N).each do |i|
    config.vm.define "server#{i}" do |server|
      server.vm.box = "centos/7"
      config.ssh.insert_key = false
      server.vm.network "private_network", ip: "192.168.3.#{i}", :netmask => "255.255.255.0"
      server.vm.provision :hosts, :sync_hosts => true
    end
  end

end

Start vagrant

$ vagrant up
$ vagrant ssh ansible_controller
$ vagrant ssh server1
$ vagrant ssh server2

The output terminal ansible install in ansible_controller as below

$ vagrant ssh ansible_controller
Last login: Thu Apr 18 14:27:27 2019 from 10.0.2.2
[vagrant@ansible_controller ~]$ ansible --version
ansible 2.7.10
  config file = None
  configured module search path = ['/home/vagrant/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.6.6 (default, Mar 29 2019, 00:03:27) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
[vagrant@ansible_controller ~]$

Initial setting of Ansible

Create a file ansible.cfg in the folder ansible as in the example below

$ cat ./ansible/ansible.cfg

The content as below

[defaults]
inventory = ./hosts
forks = 15
log_path=$HOME/ansible/ansible.log
host_key_chcking = False
gathering = smart

Create file hosts inventory as below

$ cat ./ansible/hosts

The content hosts file as below

[servers]
server1
server2

Try running Ansible

$ vagrant ssh ansible_controller
[vagrant@ansible_controller ~]$ ansible -i ansible/hosts server1 -m ping
[vagrant@ansible_controller ~]$ ansible -i ansible/hosts server2 -m ping

As the picture below

Conclusion

You have to use Vagrant create ansible. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Ansible structure playbook

In this tutorial, I wrote about the Ansible structure playbook. What does the Ansible structure playbook mean? Let’s begin!

A sample Ansible Directory Layout for staging development as below

[huupv2@server-deployment huupv2]$ tree myproject			
myproject			
├── group_vars			
│   └── nginx-server-var.yml			
├── host_vars			
│   └── server-web01.yml			
├── inventory			
│   └── my_hosts			
├── nginx-server.yml			
├── requirements			
│   └── web-server.yml			
├── roles			
└── vars			
    └── nginx_instance.yml			
			
6 directories, 6 files			

Create a structured folder for the Ansible playbook

[huupv2@server-deployment huupv2]$ mkdir myproject									
[huupv2@server-deployment huupv2]$ mkdir -p myproject/{inventory,host_vars,group_vars,vars,requirements,roles}

Create structure files for the Ansible playbook

[huupv2@server-deployment huupv2]$ touch myproject/requirements/web-server.yml							
[huupv2@server-deployment huupv2]$ touch myproject/vars/nginx_instance.yml							
[huupv2@server-deployment huupv2]$ touch myproject/group_vars/nginx-server-var.yml							
[huupv2@server-deployment huupv2]$ touch myproject/inventory/my_hosts							
[huupv2@server-deployment huupv2]$ touch myproject/host_vars/server-web01.yml							
[huupv2@server-deployment huupv2]$ touch myproject/nginx-server.yml							

For Ansible structure playbook

Server “server-deployment” installed Ansible and you want to deploy Nginx for server “server-web01” etc as in the picture below:

Working with inventory

[huupv2@server-deployment myproject]$ cat inventory/my_hosts
					
[dev-develop:children]					
tomcat-server					
nginx-server					
db-server					
					
[tomcat-server]					
					
[nginx-server]					
server-web01					
					
[db-server]					
server-db01	

Working with host_vars

set variables for individual hosts in the generated inventory file. For example, The content host_vars/nginx-server.yml file as below

nginx_instances:					
 - env_id: "dev"					
   instance_name:					
     - "DEVOPSROLES"					

Working with group_vars

set variables to particular groups. For example, The content group_vars/nginx-server-var.yml as below

nginx_version:  1.14.2					
nginx_package:					
  fullname: nginx-1.14.2-1.el6.ngx					

Working with requirements

Automatically install Ansible Galaxy roles with requirements/web-server.yml. For example, The content requirements/web-server.yml as below

## tag					
## version: v1.0.0					
## develop specify develop branch					
# version: remotes/origin/develop					
					
- src: git+https://huupv2:123456789@gitlab.com/tomcat/role-tomcat.git					
  version: v2.2					
					
- src: git+https://huupv2:123456789@gitlab.com/nginx/role-nginx.git					
  version: feature/dev-nginx					

Use ansible-galaxy to install all roles required by your playbook.

ansible-galaxy install -r requirements/web-server.yml -p roles

Working with vars

For example, The content file myproject/vars/nginx_instance.yml as below

# For devopsroles / role-nginx		
nginx_instance:		
# templates/conf/common.conf.j2		
  common_settings:		
    client_body_buffer_size: 16k		
    client_body_timeout: 60s		
    client_header_buffer_size: 1k		
    client_header_timeout: 60s		
    client_max_body_size: 1m		
    default_type: text/html		
    keepalive_timeout: 60s		
    large_client_header_buffers:		
      count: 4		
      size: 8k		
# templates/conf/nginx_site_instance.conf Used by		
  instance_indexes:		
  - index.html		
  - index.htm		
  instance_name: DEVOPSROLES							  		
# templates/conf/http[s].virtual_host.conf Used by		
  virtual_host_settings:				
    indexes:		
    - index.html		
    - index.htm		
    listen_port:		
      http: '8080'		
      https: '8443'					
    locations:				
    name: devopsroles.com		
    root: /app/DEVOPSROLES/nginx/htdocs		
    server_names:		
    - devopsroles.com		
		

Working with nginx-server.yml

- hosts: nginx-server		
  user: huupv		
  become: yes		
  roles:		
    - role-nginx		

Ansible run playbook

sudo ansible-playbook -i inventory/my_hosts nginx-server.yml -vvv --limit "server-web01"

Conclusion

Through the article, you can create a structured Ansible playbook simple. I hope will this your helpful. For more details, Ansible refers to Ansible tutorial.

Fixing ansible python broken pipe for RHEL Centos 5

Introduction

In this tutorial, How to fix run ansible “[Errno 32] Broken pipe\r\n”. I have enabled the EPEL repositories and installed the required dependencies for Python. Running Ansible on RHEL/CentOS 5 can sometimes lead to a broken pipe error. This guide provides a detailed solution to this issue, ensuring your automation processes run smoothly fix ansible python broken pipe.

The Problem

When using Ansible with Python on RHEL/CentOS 5, you might encounter a broken pipe error. This occurs due to compatibility issues between the versions of Python and Ansible. The error message typically looks like this:

Ansible python broken pipe running error

"changed": false,
   "module_stderr": "",
   "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible-tmp-1546842879.5-134879756384147/setup.py\", line 133, in ?\r\n    exitcode = invoke_module(module, zipped_mod, ANSIBALLZ_PARAMS)\r\n  File \"/tmp/ansible-tmp-1546842879.5-134879756384147/setup.py\", line 38, in invoke_module\r\n    (stdout, stderr) = p.communicate(json_params)\r\n  File \"/usr/lib64/python2.4/subprocess.py\", line 1050, in communicate\r\n    stdout, stderr = self._communicate_with_poll(input)\r\n  File \"/usr/lib64/python2.4/subprocess.py\", line 1113, in _communicate_with_poll\r\n    input_offset += os.write(fd, chunk)\r\nOSError: [Errno 32] Broken pipe\r\n",
   "msg": "MODULE FAILURE",
   "rc": 1
}
       to retry, use: --limit @/nfs/playbooks/ansible-server/apache-server.retry

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
webserver01         : ok=0    changed=0    unreachable=0    failed=1

My Ansible uses Python 2.6 and a remote server is a Virtual Machine OS Centos 5 use Python 2.4

After you install Python 2.6 on the remote server ( Centos 5). Then configure in the PATH for Python 2.6

For example, In my configuration in PATH as below

$ echo $PATH
/usr/local/bin:/bin:/usr/bin
$ which python
/usr/bin/python

Configure symbolic link for Python 2.6 on the remote server Centos 5

$ ll /usr/bin/ | grep python
$ ln -sf  /usr/bin/python26 /usr/local/bin/python

With that:

  • python 2.6 is in “//local/bin” *which is before “//bin” in the PATH
  • python 2.4 is in “//bin

And both are in the PATH

And you running the ansible-playbook command again.

FAQs

Q: Why do I need to update Python? A: The default Python version on RHEL/CentOS 5 is outdated and incompatible with newer Ansible versions, causing the broken pipe error.

Q: Can I use a different Python version? A: Yes, you can use any compatible Python version, but Python 2.7 is recommended for compatibility.

Q: What if I still encounter issues? A: Ensure all steps are followed correctly. Check the Ansible and Python versions, and verify the ANSIBLE_PYTHON_INTERPRETER path.

Conclusion

Fixing the Ansible Python broken pipe issue on RHEL/CentOS 5 involves updating Python, creating a virtual environment, installing Ansible in that environment, and configuring Ansible to use the correct Python interpreter. By following these steps, you can ensure the smooth operation of your Ansible automation tasks on older systems.

Through the article, you can use Fixing Ansible Python broken pipe for RHEL Centos 5. I hope this will be helpful for you. For more details, refer to the Ansible tutorial.

Ansible read remote file

In this tutorial, How to use Ansible to read a remote file? Ansible the essential for DevOps Roles.

Ansible read remote file using slurp module

I use the slurp module to read a remote file.

- hosts: server1
  tasks:
  - name: slurp file
    slurp:
     src: /home/vagrant/devopsroles
    register: slurp_remote_file

  - name: Read file
    debug:
     msg: "{{ slurp_remote_file['content'] | b64decode }}"

The terminal output as below

Ansible shell module

Using the shell module cat command to read a remote file

- hosts: server1
  tasks:
    - name: cat file
      shell: cat /home/vagrant/devopsroles
      register: cat_content_file

    - name: echo file
      debug:
        msg: "{{ cat_content_file.stdout }}"

The terminal output as below

Ansible fetch module

To read a remote file using Ansible, you can use the fetch module. The fetch module allows you to retrieve files from remote hosts and store them locally on the Ansible control machine.

Here’s an example task to read a remote file:

- name: Read remote file
  hosts: your_host
  gather_facts: false
  tasks:
    - name: Fetch remote file
      fetch:
        src: /path/to/remote/file.txt
        dest: /path/to/local/directory/

In this example, replace your_host with the target host or group of hosts where the remote file is located. Set the src parameter to the path of the remote file you want to read. Set the dest parameter to the local directory path where you want to store the fetched file.

Conclusion

Make sure you have proper SSH access and permissions to read the remote file on the target host(s) before running this playbook.

Through the article, you can use Ansible read remote file. I hope will this your helpful. For more details refer to Ansible tutorial.

Ansible task type of state

In this tutorial, find out the ansible task type of state. In Ansible, the state attribute is used to define the desired state of a resource or module. It is commonly used in tasks that involve package management, service management, configuration file management, and more.

The state the attribute accepts different values depending on the module being used. Ansible the essential for DevOps Roles.

Ansible task type of state

skip

– The skip task and nothing. using when: false

do –> ok

– The task is successful.

do -> changed

– The status when a change occurred in the task. Using “changed_when: yes”

do -> failed -> exit

– Using “failed_when: yes”. This task returned failed and exited.

Ansible playbook task

- hosts:
    - localhost
  tasks:
    - name: skip
      debug:
        msg: skipped
      when: false

    - name: do -> ok
      debug:
        msg: task done and return ok

    - name: do -> changed
      debug:
        msg: task has done and return changed
      changed_when: yes

    - name: do -> failed -> exit
      debug:
        msg: return failed, and exit
      failed_when: yes

The terminal output as below

These are just a few examples of the different states that can be used with Ansible modules.

The available states can vary depending on the module being used. It’s important to refer to the documentation of the specific module you’re working with to understand the available states and their behaviors.

Conclusion

Through the article, you can use the Ansible task type of state. I hope will this your helpful. For more details refer to Ansible tutorial.

Vagrant Ansible example 01

In this tutorial. You can Build infrastructure with Vagrant Ansible for testing. How to set up a local server using Vagrant Ansible.

Ansible the essential for DevOps Roles. Now, let’s go to Vagrant Ansible example 01.

My local server

[huupv@huupv my_ansible]$ cat /etc/redhat-release 
Fedora release 28 (Twenty Eight)
[huupv@huupv my_ansible]$ vagrant --version
Vagrant 2.0.2
[huupv@huupv my_ansible]$ ansible --version
ansible 2.6.4
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/huupv/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15 (default, May 16 2018, 17:50:09) [GCC 8.1.1 20180502 (Red Hat 8.1.1-1)]

Vagrant Ansible example

Step 1: You have to install Vagrant for your OS. If you have not to install Vagrant then ref to install Vagrant on Centos and install Vagrant on Ubuntu.

Step 2: Creating a folder and file your project.

example01/
├── ansible.cfg
├── playbooks
│   ├── inventory
│   │   └── hosts
│   ├── ntp.yml
│   └── templates
│   └── ntp.conf.j2
└── Vagrantfile

3 directories, 5 files

Step 3: Build infrastructure with Vagrant for testing. Define two servers: an app server and a database server in the Vagrantfiles file.

Vagrant init creates Vagrantfiles minimal file

[huupv@huupv example01]$ vagrant init --minimal

The terminal output as below

==> vagrant: A new version of Vagrant is available: 2.1.5!
==> vagrant: To upgrade visit: https://www.vagrantup.com/downloads.html

A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

The content in Vagrantfile for the app server and DB server as below

[huupv@huupv example01]$ cat Vagrantfile

The terminal output as below

Vagrant.configure("2") do |config|
config.ssh.insert_key = false
config.vm.provider :virtualbox do |vb|
   vb.customize ["modifyvm", :id, "--memory", "256"]
end
# Application server 1.
config.vm.define "app1" do |app1|
  app1.vm.hostname = "app1.dev"
  app1.vm.box = "centos/7"
  app1.vm.network :private_network, ip: "192.168.3.4"
end
# Database server.
config.vm.define "db" do |db|
  db.vm.hostname = "db.dev"
  db.vm.box = "centos/7"
  db.vm.network :private_network, ip: "192.168.3.5"
end

config.vm.provision "ansible" do |ansible|
  ansible.playbook = "playbooks/ntp.yml"
  ansible.verbose  = true
  ansible.limit = "all" # or only "nodes" group, etc.
  # Run commands as root.
  ansible.sudo = true
end
end

Ansible playbook for NTP server

Creating an inventory file for multiple servers

# Application servers

[app]

192.168.3.4 # Database server

[db]

192.168.3.5 # Group ‘multi’ with all servers

[multi:children]

app db # Variables that will be applied to all servers

[multi:vars]

ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key

Create a ntp.yml file in the folder Playbooks

- hosts: all
  tasks:
  - name: Ensure NTP (for time synchronization) is installed.
    yum: name=ntp state=installed
  - name: Configure NTP
    template: src=ntp.conf.j2 dest=/etc/ntp.conf
    notify:
           - restart ntpd
  - name: Ensure NTP is running.
    service: name=ntpd state=started enabled=yes

Create ntp.conf.j2 file template

statistics loopstats peerstats clockstats
filegen loopstats file loopsstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

#server your_NTP_server_IP
server 0.rhel.pool.ntp.org iburst
server 1.rhel.pool.ntp.org iburst
server 2.rhel.pool.ntp.org iburst
server 3.rhel.pool.ntp.org iburst

restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery
restrict 127.0.0.1
restrict ::1

Vagrant run ansible local

Running vagrant up the first time. Vagrant automatically provisions the newly-minted VM. Run “vagrant provision” again after the VM has been created.

The first run vagrant up

[huupv@huupv example01]$ vagrant up

The terminal output as below

Run vagrant provision again.

[huupv@huupv example01]$ vagrant provision

The terminal output as below

The result Vagrant Ansible example, The terminal output as below

[huupv@huupv example01]$ vagrant ssh app1
Last login: Sat Sep 15 06:26:42 2018 from 10.0.2.2
[vagrant@app1 ~]$ cat /etc/ntp.conf 
statistics loopstats peerstats clockstats
filegen loopstats file loopsstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

#server your_NTP_server_IP
server 0.rhel.pool.ntp.org iburst
server 1.rhel.pool.ntp.org iburst
server 2.rhel.pool.ntp.org iburst
server 3.rhel.pool.ntp.org iburst

restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery
restrict 127.0.0.1
restrict ::1
[vagrant@app1 ~]$ exit
logout
Connection to 127.0.0.1 closed.
[huupv@huupv example01]$ vagrant ssh db
Last login: Sat Sep 15 06:26:42 2018 from 10.0.2.2
[vagrant@db ~]$ cat /etc/ntp.conf 
statistics loopstats peerstats clockstats
filegen loopstats file loopsstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

#server your_NTP_server_IP
server 0.rhel.pool.ntp.org iburst
server 1.rhel.pool.ntp.org iburst
server 2.rhel.pool.ntp.org iburst
server 3.rhel.pool.ntp.org iburst

restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery
restrict 127.0.0.1
restrict ::1
[vagrant@db ~]$ exit
logout
Connection to 127.0.0.1 closed.
[huupv@huupv example01]$

Conclusion

Through the article, you can use Vagrant Ansible example of best practice. I hope will this your helpful. For more details refer to Ansible tutorial.

Ansible playbook NGINX + PHP

In this tutorial, I will deploy  Ansible playbook Nginx and PHP for remote server centos 7. Ansible the essential for DevOps Roles.

My system:

Control server: DevopsRoles —–> Remote server: webserver

Control server:

Installed Ansible “I use root account running Ansible, You are understand? Please careful

Remote server:

  •  Install webserver Nginx and PHP
  •  Create a user huupv with sudo privileges ( more details ref to linux create user )

Ansible playbook NGINX + PHP

Create a folder and file for Ansible Nginx

[root@DevopsRoles ~]# pwd
/root
[root@DevopsRoles ~]# mkdir ansible-nginx
[root@DevopsRoles ~]# mkdir ansible-nginx/inventory
[root@DevopsRoles ~]# vi ansible-nginx/webserver-main.yml

The content  webserver-main.yml file as below

- name: install and configure the web server
  hosts: webserver
  remote_user: huupv
  become: yes

  roles:
    - nginx
    - php

Create file hosts

[root@DevopsRoles ~]# vi ansible-nginx/inventory/hosts

The content is as below:

[webserver]
192.168.1.113

In this command, checking for communication use the ping module ansible.

[root@DevopsRoles ansible-nginx]# ansible all -i inventory/hosts -m ping

192.168.1.113 | SUCCESS => {
"changed": false, 
"ping": "pong"
}

Ansible roles Nginx and PHP

[root@DevopsRoles ~]# mkdir ansible-nginx/roles
[root@DevopsRoles ~]# cd ansible-nginx/roles
[root@DevopsRoles roles]#

create the role for Nginx and PHP. Using ansible-galaxy creates a template

[root@DevopsRoles roles]# ansible-galaxy init nginx
- nginx was created successfully
[root@DevopsRoles roles]# ansible-galaxy init php
- php was created successfully

Ansible roles Nginx create by ansible-galaxy

Ansible structure folder and file as below

nginx
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
└── main.yml

8 directories, 8 files

Setting ansible task Nginx

The modify nginx/tasks/main.yml for role Nginx

[root@DevopsRoles roles]# vi nginx/tasks/main.yml

The content main.yml file as below

# tasks file for nginx
- name: Install NGINX.
  yum: name=nginx
- command: chkconfig nginx on
- command: service nginx restart
- name: Install NGINX.
  yum: name={{ item }}
  with_items:
    - http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm

  # enabled=0
  - replace: dest=/etc/yum.repos.d/{{ item }} regexp="enabled *= *1" replace="enabled=0"
  with_items:
     - nginx.repo
  - yum: name=nginx
  - command: chkconfig nginx on
  - command: service nginx restart

Ansible roles PHP create by ansible-galaxy

Ansible structure folder and file as below

php
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
└── main.yml

8 directories, 8 files

Setting ansible task PHP

The Modify php/tasks/main.yml for role PHP

[root@DevopsRoles roles]# vi php/tasks/main.yml

The content is as below:

# tasks file for php
- name: Install PHP
  yum: name={{ item }} state=present enablerepo=epel
  with_items:
   - php70u-cli
   - php70u-common
   - php70u-fpm
   - php70u-fpm-nginx
   - php70u-json
   - php70u-mysqlnd
   - php70u-opcache
   - php70u-pdo

Ansible tasks/main.yml installed modules of PHP from yum in succession. Convenient!

Run ansible playbook

Run check the syntax of the Ansible playbook

[root@DevopsRoles ansible-nginx]# ansible-playbook -C -i inventory/hosts webserver-main.yml

Checking result syntax ok run ansible-playbook again

[root@DevopsRoles ansible-nginx]# ansible-playbook -i inventory/hosts webserver-main.yml

The confirm installed Nginx and PHP on a host web server

Nginx version

PHP version

Remember to customize the playbook and PHP-FPM configuration based on your specific requirements.

Conclusion

Through the article, you can use the Ansible playbook NGINX + PHP as above. I hope will this your helpful. For more details refer to the Ansible tutorial.

Ansible tutorial beginners

In this article, I will guide Ansible tutorial beginners. How to create ansible playbook? Ansible the essential for DevOps Roles.

  1. What is Ansible
  2. Ansible best practices

The environment for my system as below

[root@DevopsRoles ~]# ansible --version
ansible 2.6.2
[root@DevopsRoles ~]# python --version
Python 2.7.5

Server01: Control Machine 

  • VM01: DevopsRoles (Installed Ansible)
  • IP: 192.168.1.112

Server02: Target

  • VM02: a web server
  • IP: 192.168.1.113

What is Ansible

Introduction to Infrastructure as Code by Ansible.

“Ansible is the simplest way to automate apps and IT infrastructure. Application Deployment + Configuration Management + Continuous Delivery”

Here’s a beginner-friendly Ansible tutorial to get you started:

Ansible tutorial best practices

Installation of Ansible

Guide install Ansible on Centos/Ubuntu/Redora

Step by step for Ansible

Create the folder for Ansible

[root@DevopsRoles ~]# mkdir ansible
[root@DevopsRoles ~]# mkdir ansible/{inventory,group_vars,files,templates}

Create files for Ansible

[root@DevopsRoles ~]# pwd
/root
[root@DevopsRoles ~]# touch ansible/inventory/hosts
[root@DevopsRoles ~]# touch ansible/group_vars/webserver.yml
[root@DevopsRoles ~]# touch ansible/files/file_webserver
[root@DevopsRoles ~]# touch ansible/templates/template_webserver.j2
[root@DevopsRoles ~]# touch ansible/test_ansible.yml
[root@DevopsRoles ~]# touch ansible/main.yml

Ansible structure folder and file as below

ansible/
├── files
│   └── file_webserver
├── group_vars
│   └── webserver.yml
├── inventory
│   └── hosts
├── main.yml
├── templates
│   └── template_webserver.j2
├── test_ansible.retry
└── test_ansible.yml

To create ssh-keygen from VM01 DevopsRoles communication to VM02 webserver do not enter the password.

[root@DevopsRoles ~]# ssh-keygen -t rsa
[root@DevopsRoles ~]# ssh-copy-id root@192.168.1.113

The terminal output as below

I’m running Ansible playbook as root, I guess you understand. Please be careful.

In this inventory file, we have a host named 192.168.1.113 in the group “[webserver]” (VM02).

[webserver]
192.168.1.113

In this command, checking for communication use the ping module ansible.

[root@controller ansible] ansible all -i inventory/hosts -m ping

The terminal output as below

[root@DevopsRoles ansible]# ansible all -i inventory/hosts -m ping
192.168.1.113 | SUCCESS => {
"changed": false, 
"ping": "pong"
}

Create Ansible playbook

To create a webserver.yml file.

[root@DevopsRoles ansible]#  cat group_vars/webserver.yml

---
message: "Hello Ansible !" 
Info: 
   huu: 
     age: 29 
   songoku: 
     age: 100 
   laika: 
     age: 30

This file describes group variables. To create a test_ansible.yml file

[root@DevopsRoles ansible]# cat test_ansible.yml

---
- hosts: webserver
  user: root
  tasks:
    - name: output message.
      debug: msg="{{ message }}"

    - name: output info
      debug: msg="We want {{ item.value.age }} {{ item.key }} !" 
      with_dict: "{{ Info }}"

Run ansible-playbook

[root@DevopsRoles ansible]# ansible-playbook -i inventory/hosts test_ansible.yml

The terminal output as below

Example Ansible playbook roles

Ansible structure folder and file as below

ansible/
├─inventory/
│ └─hosts
├─group_vars/
│ └─webserver.yml
├─files/
│ └─file_webserver
├─templates/
│ └─template_webserver.j2
├─roles/
│ ├─role-common/
│ │ └─tasks/
│ │  └─main.yml
│ └─role-web/
│   └─tasks/
│   └─main.yml
├─test.yml
├─main.yml
└─master.yml

Creating the folder and file for ansible-playbook roles

[root@DevopsRoles ansible]# pwd
/root/ansible
[root@DevopsRoles ansible]# touch master.yml
[root@DevopsRoles ansible]# mkdir roles
[root@DevopsRoles ansible]# mkdir roles/{role-common,role-web}
[root@DevopsRoles ansible]# mkdir roles/role-common/tasks
[root@DevopsRoles ansible]# mkdir roles/role-web/tasks
[root@DevopsRoles ansible]# touch roles/role-common/tasks/main.yml
[root@DevopsRoles ansible]# touch roles/role-web/tasks/main.yml

Package operation can be done with the Yum module etc. It is an image as below.

- name: install packages from yum
  yum: name={{ item }} state=latest
  with_items:
    - nginx

In the above code, “Nginx” is installed”, but if “state=absent” it will be a code indicating that it is not installed.

You can set up CRON job using the CRON module.

- name: register cron job
  cron: name="check ping" day="*/2" hour="12" minute="0" job="ping -c 3 192.168.1.113"

Of course, you can create directories and place files in Ansible. Directory creation is done with the file module.

- name: create directories
  file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
  with_items:
    - { "path":"/opt/ansible", "owner":"root", "group":"root", "mode":"755" }
    - { "path":"/opt/data", "owner":"root", "group":"root", "mode":"755" }

Copy Static file using copy module ansible

- name: copy files
  copy: src=./files/file_webserver dest=/opt/ansible/file_webserver owner=root group=root mode=0755

To copy the Dynamic file for Ansible

- name: copy template files
  template: src=./templates/template_webserver.j2 dest=/opt/ansible/template_webserver owner=root group=root mode=0755

I have written in jinja2 file format.

cat templates/template_webserver.j2

#This is a jinja template file.
{{ message }}
#jinja template can extract variables. like, ...
{% for key,value in Info.iteritems() %}
I am {{ value.age }} {{ key }} !
{% endfor %}

In the jinja template, you can also use variables in almost the same way as in Playbook.
I can also iterate with for statement like with_dict, but here you can use it without putting the item.

The final, all the contents so far.

[root@DevopsRoles ansible]# cat main.yml

The content main.yml file as below

- hosts: webserver
  user: root
  tasks:
    - name: install packages from yum
      yum: name={{ item }} state=latest
      with_items:
        - nginx

- name: register cron job
      cron: name="check ping" day="*/2" hour="12" minute="0" job="ping -c 3 192.168.1.113"

    - name: create directories
      file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
      with_items:
        - { "path":"/opt/ansible", "owner":"root", "group":"root", "mode":"755" }
        - { "path":"/opt/data", "owner":"root", "group":"root", "mode":"755" }

    - name: copy files
      copy: src=./files/file_webserver dest=/opt/ansible/file_webserver owner=root group=root mode=0755

    - name: copy template files
      template: src=./templates/template_webserver.j2 dest=/opt/ansible/template_webserver owner=root group=root mode=0755

Check Mode is a mode that does not actually change, you can check which part will be changed when you run Playbook. Generally, it is called Dry run mode for Ansible. If you give –check as an option, it works in Check Mode.

[root@DevopsRoles ansible]# ansible-playbook --check -i inventory/hosts main.yml

The screen output terminal:

Let’s use the -v option to see it in more detail.

[root@DevopsRoles ansible]# ansible-playbook --check -i inventory/hosts main.yml -v

Run Ansible Playbook.

[root@controller ansible]# ansible-playbook -i inventory/hosts main.yml

The screen output terminal:

Using Ansible role

The tasks are described collectively in one YAML file so far, but this does not work well when creating similar hosts.
Let’s cut out some of the tasks as roles and try to make them into parts.

[root@DevopsRoles ansible]# cat master.yml

The content master.yml file as below

- hosts: webserver
  user: root
  tasks:
    - name: register cron job
      cron: name="check ping" day="*/2" hour="12" minute="0" job="ping -c 3 192.168.1.113"

  roles:
    - role-common
    - role-web

[root@DevopsRoles ansible]# cat roles/role-common/tasks/main.yml

The content main.yml file for role-common as below

- name: install packages from yum
  yum: name={{ item }} state=latest
  with_items:
    - nginx

- name: create directories
  file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
  with_items:
    - { "path":"/opt/ansible", "owner":"root", "group":"root", "mode":"755" }

- name: copy files
  copy: src=./files/file_webserver dest=/opt/ansible/file_webserver owner=root group=root mode=0755

[root@DevopsRoles ansible]# cat roles/role-web/tasks/main.yml

The content main.yml for role-web as below

- name: install packages from yum
  yum: name={{ item }} state=latest
  with_items:
   - nginx

- name: create directories
  file: path={{ item.path }} owner={{ item.owner }} group={{ item.group }} mode=0{{ item.mode }} state=directory
  with_items:
    - { "path":"/opt/data", "owner":"root", "group":"root", "mode":"755" }

- name: copy template files
  template: src=./templates/template_webserver.j2 dest=/opt/ansible/template_webserver owner=root group=root mode=0755

Do not say that handling with_items is not good just because I just cut out (lol)

The role called by roles is searched under the name under the roles directory, and main.yml directly under tasks is executed.
You can use dependencies etc to have a dependency on the role, but we will not handle it this time.

Let’s do it.

[root@DevopsRoles ansible]# ansible-playbook --check -i inventory/hosts master.yml

The screen output terminal:

Run ansible-playbook

[root@DevopsRoles ansible]# ansible-playbook -i inventory/hosts master.yml

Conclusion

This tutorial provides a basic introduction to get you started with the Ansible tutorial. As you gain more experience, you can explore advanced topics like inventory management, playbook organization, and integration with other tools and systems.

Through the article, you can use Ansible tutorial beginners as above. I hope will this your helpful. For more details refer to Ansible tutorial.

How to install Ansible on Centos/ Ubuntu/Fedora

Introduction

In this tutorial, I guide how to install Ansible on Centos 7/ Ubuntu 14.04 / Fedora. Ansible is an Automation tool for IT Management. It’s useful for System Admin, and DevOps to build Automation Configure Management. Ansible the essential for DevOps Roles.

To install Ansible on CentOS, Ubuntu, or Fedora, you can follow the instructions below for each respective operating system:

Requirements

  • Control Machine: Run Ansible.
  • Remote server: Deploy and Configure such as Tomcat,  Nginx, Apache, and so forth from Control Machine.

Control Machine and remote server communication through SSH key Authentication.

How to install Ansible on Control Machine

For Centos 7 and RHEL 7

Open a terminal on your CentOS machine.

 # rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
 # yum install ansible

For Ubuntu 14.04 / 15.04

 $ sudo apt-get install software-properties-common
 $ sudo apt-add-repository ppa:ansible/ansible
 $ sudo apt-get update
 $ sudo apt-get install ansible

Checking Ansible version

 $ ansible --version

For example, The output Ansible version

ansible 2.5.3
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

That’s it! Ansible should now be installed on your CentOS, Ubuntu, or Fedora machine. You can start using Ansible to automate your IT infrastructure tasks.

Conclusion

Thought this article, How to install Ansible on Centos/Ubuntu and Fedora. In the next post, I installed and configured Nginx automation from Control Machine for the Remote server. Thank you for reading the DevopsRoles page!