Showing posts with label Ansible. Show all posts
Showing posts with label Ansible. Show all posts

Monday, October 31, 2022

Rotate Keys on multiple EC2 instances using Ansible

Description: Here I have explained, How to rotate/replace key pairs on EC2 instances using Ansible

Setup:

  • 2 Instances with same key pair 
  • 2 Key pair [one is existing and one is new]
  • IAM user with Administrator privilege

Procedure:

After create 2 Virtual Machines with same Key pair, create one more new key pair file for replacement.
Key name are as follow:
  • Old-key.pem [current key]
  • New-Key.pem [New key] 
Now I am creating one IAM user with Administrator privilege from AWS console as follow




 


















After creating user, download CSV file for reference in variable file for authentication. 

First creating variable file with key.vars file as follow:

access_key: "XXXXXX5UIGMCGDXXXXXX" secret_key: "XXXXXXVxsLGhbdrqz+I2IhnnrG+XXXXXXX" region: "us-west-2" #----> Example: "ap-south-1" old_key: "Old-key" #----> Upload this Pem file in the same directory with 400 Permission. new_key: "New-Key" system_user: "ubuntu" ssh_port: 22

Note:
  •  access_key = IAM user access key
  •  secret_key = IAM user secret key
  •  region = Infrastructure host region 
  •  old_key = current / existing key name 
  •  new_key = new key which need to replace
  •  system_user = ubuntu [ I have used ubuntu as operating system so default user is ubuntu]
After creating variable files, changing the both key file permission to 0400 using chmod command line

Now going to create main.yml as follow for replacement of key as follow



--- - name: "Creation of the Ansible Inventory Of EC2 Instances in which Key To Be Rotated" hosts: localhost vars_files: - key.vars tasks: # --------------------------------------------------------------- # Getting Information of the EC2 instances in which Key To Be Rotated # --------------------------------------------------------------- - name: "Fetching Details About EC2 Instance" ec2_instance_info: aws_access_key: "{{ access_key }}" aws_secret_key: "{{ secret_key }}" region: "{{ region }}" filters: "key-name": "{{ old_key }}" instance-state-name: [ "running"] register: ec2 # ------------------------------------------------------------ # Creating Inventory Of EC2 With Old SSH-keyPair # ------------------------------------------------------------ - name: "Creating Inventory " add_host: name: "{{ item.public_ip_address }}" groups: "aws" ansible_host: "{{ item.public_ip_address }}" ansible_port: "{{ ssh_port }}" ansible_user: "{{ system_user }}" ansible_ssh_private_key_file: "{{ old_key }}.pem" ansible_ssh_common_args: "-o StrictHostKeyChecking=no" with_items: - "{{ ec2.instances }}" no_log: true - name: "Updating SSH-Key Material" hosts: aws become: true gather_facts: false vars_files: - key.vars tasks: - name: "Register current SSH Authorized_key file of the system user" shell: cat /home/"{{system_user}}"/.ssh/authorized_keys register: oldauth - name: "Creating New SSH-Key Material" delegate_to: localhost run_once: True openssh_keypair: path: "{{ new_key }}" type: rsa size: 4096 state: present - name: "Adding New SSH-Key Material" authorized_key: user: "{{ system_user }}" state: present key: "{{ lookup('file', '{{ new_key }}.pub') }}" - name: "Creating SSH Connection Command" set_fact: ssh_connection: "ssh -o StrictHostKeyChecking=no -i {{ new_key }} {{ ansible_user }}@{{ ansible_host }} -p {{ ansible_port }} 'uptime'" - name: "Checking Connectivity To EC2 Using Newly Added Key" ignore_errors: true delegate_to: localhost shell: "{{ ssh_connection }}" - name: "Executing the Uptime command on remote servers" command: "uptime" register: uptimeoutput - debug: var: uptimeoutput.stdout_lines - name: "Removing Old SSH Public Key and adding New SSH Public Key to authorized_key" authorized_key: user: "{{ system_user }}" state: present key: "{{ lookup('file', '{{ new_key }}.pub') }}" exclusive: true - name: "Print Old authorized_keys file" debug: msg: "SSH Public Keys in Old authorized_keys file are '{{ oldauth.stdout }}'" - name: "Print New authorized_keys file" shell: cat /home/"{{system_user}}"/.ssh/authorized_keys register: newauth - debug: msg: "SSH Public Keys in New authorized_keys file are '{{ newauth.stdout }}'" - name: "Renaming new Private Key Locally" delegate_to: localhost run_once: True shell: | mv {{ new_key }} {{ new_key }}.pem chmod 400 {{ new_key }}.pem - name: "Removing Old SSH public key From AWS Account" delegate_to: localhost run_once: True ec2_key: aws_access_key: "{{ access_key }}" aws_secret_key: "{{ secret_key }}" region: "{{ region }}" name: "{{ old_key }}" state: absent - name: "Adding New SSH public key to AWS Account" delegate_to: localhost run_once: True ec2_key: aws_access_key: "{{ access_key }}" aws_secret_key: "{{ secret_key }}" region: "{{ region }}" name: "{{ new_key }}" key_material: "{{ lookup('file', '{{ new_key }}.pub') }}" state: present

After saving above file, open terminal and run ansible playbook using command line as follow. Kindly note run ansible command as root user with sudo rights 

# ansible-playbook main.yml





















Now verify the ssh connection with new keys.

Friday, June 10, 2022

Run Ansible Playbook using Jenkins Pipeline

Description: Here I have explained, How to install Ansible plugin in Jenkins, integrate it and Run Ansible playbook using Jenkins Freestyle Project.


Setup:

  1. Ansible install in same machine as Jenkins
  2. Jenkins with require plugins
  3. Client machine for install Nginx
To run the ansible job from Jenkins, we need  to install ansible plugin from Jenkins 













To login and authentication in Remote client machine, we need to setup user with key in ansible/Jenkins machine. Here in this example, I am using Ubuntu user and generate key using below command.

$ ssh-keygen -t rsa



















After running above command you will find 2 key files. One is Private key [id_rsa] and Public Key [id_rsa.pub]  After generating keys, copy public key to destination client machine's  root user  authorisation file.

Here I am going to copy key to root user because, I will use root to login using same user via ansible playbook and install Nginx in destination client server.

Public key file [id_rsa.pub] content looks like as follow:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWokq0EqR3F6/aFJRYP2P7vsB1DOORosEgmfB9DYG5cLXKlumCoEonG/uZcvns8zBHAgCfSq/gysj9hMmml6KUWfwl7V6/6ethJrpQc3xIQeSamFiGiCJuz9s57y7O95pq/TL9saLJDi2TvmfheLvtUig98CFEQrW+Bvv0AMwHAsQCCqyGhRhdUlnijVoryXlVBpnMZ1GAbzMSeOrF/9t6pfNOujFw7PPK6a45VafcmHgIpPtnxWOzyf/WhpsZ11l+eezyBMQT14Cv5pYnMLswqi9HazDLwHkz81wu+e34r6Uo5vQB/ViIMOyMVZuKwMAokVH5+NI/M5OJlMmbyQPmlWZdtprrSiD59Nb59lFe0wk5rTYoOm6lXfPCUygKkrPvX/co2/SyOc8/zsAtcRSkbjmi6oK7QXSl8GDa/pXy/g1PH1SAkHHg9/YNQbNW1SlvmvYyMxGLLxRkQ42Hj2k396xMc2G2coXXB4ikxxErhQEqHrnv24J0/TzGykImV0M= ubuntu@ip-172-31-11-49

Copy file content to destination machine's root folder authorized_keys as follow











After copy key, need to setup user credentials in Jenkins. To Setup user open Jenkins console and navigate to Manage Jenkins --> Manage Credentials --> Add Credentials 

















Fill details like, username and private key of ubuntu user as follow










































After saving the credentials, I am going to create one playbook in ansible for setup Nginx in ansible/jenkins as follow.

Define Host in ansible hosts file as follow:

[server] 172.31.11.49 ## Ip address of client machine in which we are going to setup Nginx 


Please create playbook.yml for install nginx  in client machine

--- - hosts: server remote_user: root tasks: - name: ensure apache is at the latest version apt: name=nginx state=latest

Define Key file location and user details in ansible.cfg [Located on /etc/ansible directory]  as follow. Also I have copied both the key files in Ansible directory. 

[defaults] host_key_checking = False private_key_file = /etc/ansible/id_rsa remote_user = root remote_tmp = /tmp/

After setting up all the above ansible thing, I am going to test the connection from Ansible to client machine using below command 

# ansible -m ping server 












After showing success, I am going to create Free style project in Jenkins. To create project navigate to Dashboard --> New Item --> Give Name of project --> Select Free Style Project




















Navigate to Build step and select Add Build Step --> Select Invoke Ansible Playbook






















Fill the require details like playbook path, host file path and credentials [setup as previous with private key] and save / apply the project




















After setup  project, Open it and click on Build Now 




















Once build process completed, Open the output of the build. It looks like as follow



















Also we can check the nginx version as follow



Wednesday, February 16, 2022

Install LAMP on Ubuntu using Ansible

Description: Here I have explained, How to install LAMP on ubuntu using Ansbile by creating separate roles for each.

Install Ansible on Ubuntu

# apt install ansible

# ansible --version   [To verify the ansible version]


Generate SSH keys and copy it to destination server

To communicate/Authorise Ansible server to destination server need to generate ssh keys to destination server using URL

Setup Host in Ansible host file 

Open host configuration file under /etc/ansible/hosts file and add host as follow:

# vi /etc/ansible/hosts

#[dbservers]
# #db01.intranet.mydomain.net #db02.intranet.mydomain.net # Here's another example of host ranges, this time there are no # leading 0s: #db-[99:101]-node.example.com [web] 20.124.15.109

Verify the Ansible result by ping using below command

# ansible -m ping web


Create Directory for different roles and variable file 

Navigate to folder and create different roles for each components. Here, I am going to create for 3 roles [Apache, PHP and MySQL] using below command 

# ansible-galaxy role init apache
# ansible-galaxy role init php
# ansible-galaxy role init mysql

Run tree command to verify the folder structure for all three roles

# tree


Declare Variables for each role: First I am going to declare variable for each role. For variable I am creating role for group variable using below command 
# ansible-galaxy role init groupvar

Once variable role created navigate to var folder in groupvar and create  variable file as follow 

# cd /home/serverapprunner/Apache/groupvar/vars
# vi main.yml

--- ### Variables for LAMP ### http_host: techserverweb.com http_conf: techserverweb.com.conf http_port: 80 app_user: www-data sudo_user: root mysql_root_password: P@ssw0rd123 php_version: 7.4

Here, I have defined variable like host name, configuration, Port number, etc..

Apache: After setup main variable file, first I am going to create task, handlers and file for Apache 

Navigate to Apache folder under role folder. Open tasks folder and paste below content in main.yml file 

--- - name: Install prerequisites apt: name={{ item }} update_cache=yes state=latest force_apt_get=yes loop: [ 'aptitude' ] #Apache Configuration - name: Install Apache Packages apt: name={{ item }} update_cache=yes state=latest loop: [ 'apache2' ] - name: Create document root file: path: "/var/www/{{ http_host }}" state: directory owner: "{{ app_user }}" mode: '0755' - name: Set up Apache virtualhost template: src: "files/apache.conf.j2" dest: "/etc/apache2/sites-available/{{ http_conf }}" - name: Enable new site shell: /usr/sbin/a2ensite {{ http_conf }} #- name: Disable default Apache site # shell: /usr/sbin/a2dissite 000-default.conf # when: disable_default # notify: Reload Apache # UFW Configuration - name: "UFW - Allow HTTP on port {{ http_port }}" ufw: rule: allow port: "{{ http_port }}" proto: tcp - name: Reload Apache service: name: apache2 state: reloaded - name: Restart Apache service: name: apache2 state: restarted

Open files directory and create apache.conf.j2 file and paste content as follow

<VirtualHost *:{{ http_port }}> ServerAdmin webmaster@localhost ServerName {{ http_host }} ServerAlias www.{{ http_host }} DocumentRoot /var/www/{{ http_host }} ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/{{ http_host }}> Options -Indexes </Directory> <IfModule mod_dir.c> DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm </IfModule> </VirtualHost>

Open handler directory and create main.yml file, Paste content as follow. To restart the apache2 service after installation
--- - name: Reload Apache service: name: apache2 state: reloaded - name: Restart Apache service: name: apache2 state: restarted

PHP: After setup for Apache, Creating yaml file for defaults, files, tasks and handlers

Open defaults folder and define php modules in default.yml file 

--- # defaults file for php7x php_modules: - fpm - mysql - cli - common - json - opcache - gd - intl - curl - mbstring - zip - xml - soap - bcmath - dev

Open tasks folder and create default.yml file as follow to install PHP7.4 

--- - name: Setting Default Language shell: LC_ALL=en_US.UTF-8 - apt_repository: repo: ppa:ondrej/php - name: Update APT shell: apt-get update - name: Install php{{ php_version }} apt: name: "php{{ php_version }}-{{ item }}" state: present with_items: "{{ php_modules }}" - name: Copy PHP info to Webroot template: src: "files/info.php.j2" dest: "/var/www/{{ http_host }}"

Create info.php.j2 file for phpinfo page copy to virtual host location in files directory as follow

<?php phpinfo();

MySQL: After setup PHP, creating main.yml file under tasks directory as follow

--- - name: Install prerequisites apt: name={{ item }} update_cache=yes state=latest force_apt_get=yes loop: [ 'aptitude' ] #Install MariaDB server - name: Install MariaDB Packages apt: name={{ item }} update_cache=yes state=latest loop: [ 'mariadb-server', 'python3-pymysql' ] # Start MariaDB Service - name: Start MariaDB service service: name: mariadb state: started become: true # MariaDB Configuration - name: Sets the root password mysql_user: name: root password: "{{ mysql_root_password }}" login_unix_socket: /var/run/mysqld/mysqld.sock - name: Removes all anonymous user accounts mysql_user: name: '' host_all: yes state: absent login_user: root login_password: "{{ mysql_root_password }}" - name: Removes the MySQL test database mysql_db: name: test state: absent login_user: root login_password: "{{ mysql_root_password }}"

After setup all three roles, create deploy.yml file at root folder path. In which I have define roles which need to run

--- - name: apply common configuration to all nodes hosts: all become: yes become_method: sudo vars_files: - roles/groupvar/vars/main.yml roles: - apache - mysql - php

Run the ansible playbook by run below command 

# ansible-playbook deploy.yml


Verification: After successfully deploy verify Apache, PHP and MySQL 

MariaDB:


Apache:



PHP:




Wednesday, May 5, 2021

Create S3 Bucket in AWS using Ansible

 Description: Here I have explained, How to Create Bucket in AWS using Ansible 

Create IAM user from AWS:

  • IAM user need to Authorize Ansible Playbook to manage the S3 bucket
  • Open IAM console from AWS and navigate to IAM service 

  • Give S3 Full Access to IAM created user

  • Once the user created, download the user detail .csv file which contains Access Key and Secret ID

Install Require Ansible Packages in Ansible server
  • boto
    # pip install boto
  • boto3
    # pip install boto3
  • python version >= 2.6
    # yum install python 
Create ssh key for localhost to authorize

# ssh-keygen

  • Copy generated ssh key to authorization keys 
    # vi /root/.ssh/authorized_keys


Prepare Playbook to create S3 Bucket with Name "techblogalbucket" in "us-east-1" Region and with Public access

# vi Create_Bucket.yml --- - hosts: localhost tasks: - name: Create an S3 bucket become: true aws_s3: aws_access_key=XXXXXXXX aws_secret_key=XXXXXXXXXXXXXXX bucket=techblogalbucket mode=create permission=public-read region=us-east-1

  • Run yml file using ansible-playbook command
# ansible-playbook s3_create.yml

  • After successfully run yaml file verify S3 bucket in AWS console 


Monday, April 5, 2021

Install LAMP using Ansible Role

Description: Here I have explained, What is Ansible Role? How to install LAMP in Centos using Ansible Role?

What is Ansible Role?

Ansible role is a set of tasks to configure a host to serve a certain purpose like install and configure services. Roles are defined using YAML files with a predefined directory structure. A role directory structure contains directories: defaults, vars, tasks, files, templates, meta, handlers. Each directory must contain a main.yml file that contains relevant content. Below is the description of each directory

  1. defaults: contains default variables for the role. Variables in default have the lowest priority so they are easy to override.
  2. vars:  contains variables for the role. Variables in vars have higher priority than variables in the defaults directory.
  3. tasks: contains the main list of steps to be executed by the role.
  4. files: contains files that we want to be copied to the remote host. We don’t need to specify a path of resources stored in this directory.
  5. templates: contains file template which supports modifications from the role. We use the Jinja2 templating language for creating templates.
  6. meta: contains metadata of role like an author, support platforms, dependencies.
  7. handlers: contains handlers that can be invoked by “notify” directives and are associated with service.
How to Install LAMP [Linux, Apache, MySQL, PHP] in Centos using Ansible?

Apache: 
  • Create a role for Apache using ansible-galaxy command 
    # ansible-galaxy init apache

  • After creating the role navigate to the task directory under the apache role directory and open main.YAML file [Already created with role] and paste below content to install and start httpd service

--- # tasks file for apache - name: ensure apache is at the latest version yum: name=httpd state=latest - name: ensure service started service: name=httpd state=started

MySQL:
  • Create a role for MySQL using ansible-galaxy command
    # ansible-galaxy init MySQL

  • After creating role crate task and handler file on each respective directories
  • First I am going to create task file for MySQL 5.7 as follow
    # cd /etc/ansible/roles/MySQL/tasks/
    # vi main.yml

--- - name: Install MySQL 5.7 repo yum: name=http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm state=present - name: Install MySQL 5.7 yum: pkg={{ item }} with_items: - mysql-community-server - mysql-community-client - MySQL-python - name: Start the MySQL service service: name=mysqld state=started enabled=true - name: Change mysql root password and keep track in shell: | password_match=`awk '/A temporary password is generated for/ {a=$0} END{ print a }' /var/log/mysqld.log | awk '{print $(NF)}'` echo $password_match mysql -uroot -p$password_match --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'P@ssw0rd123'; flush privileges; " echo "[client]" user=root password=PassW0rd > /root/.my.cnf args: creates: /root/.my.cnf register: change_temp_pass notify: restart mysqld - meta: flush_handlers - debug: var: change_temp_pass
  • After creating task file, I am going to create handler to restart mysql service as follow
    # /etc/ansible/roles/MySQL/handlers
    # vi main.yaml
--- # handlers file for mysql - name: restart mysqld service: name=mysqld state=restarted

PHP:
  • Create Role for PHP using ansible-galaxy command 
    # ansible-galaxy init php
  • After creating role open task folder and create yaml file to install php as follow
    # cd /etc/ansible/roles/php/tasks
    # vi main.yml
--- # tasks file for php - name: ensure php is at the latest version yum: name=php state=latest

Install LAMP:
  • After creating all tasks file now creating YAML file for LAMP installation with roles 
    # vi LAMP.yaml
--- - hosts: all roles: - apache - MySQL - php
  • Run YAML file using the ansible-playbook command 
         # ansible-playbook LAMP.yaml



Verification:
Now I am verifying each component on the Destination server

PHP:

MySQL:

Apache:


Saturday, April 3, 2021

Create Partition using Ansible

Description: Here I have explained, How to Create Partition, Format, and Mount using Ansible


Procedure:

  • Ansible uses Parted module to manage the partition. Below is the Yaml file to create a partition of 10GB on drive

### Create partition of 10 GB on /dev/xvdb device and mount on /mnt/storage --- - name: create partition hosts: web remote_user: root become: yes tasks: - name: Create a new ext4 primary partition parted: device: /dev/xvdb number: 1 state: present part_start: 2MiB part_end: 10GiB - name: Format the Disk filesystem: fstype: ext4 dev: /dev/xvdb1 - name: create the Directory file: path: /mnt/storage state: directory mode: '0755' - name: Mount Prtition mount: path: /mnt/storage src: /dev/xvdb1 fstype: ext4 state: mounted











  • Verify partition after run playbook


Friday, April 2, 2021

Managing Files using Ansible

Description: Here I have explained, How to create a blank file? How to copy files to a remote PC? How to add one and multiple lines in the file?

How to Create a blank file?
Below is the YAML file to create a blank file in a remote machine

##Create blank file with Test_Ansible.txt --- - hosts: web tasks: - name: Create blank file file: path: "/root/Test_Ansible.txt" state: touch



How to Copy a file to a remote machine from a local machine?
Below is the YAML file to copy the file to remote machine from local machine|
--- - hosts: web tasks: - name: Copy from Local to Remote Target Machine with 'copy' copy: src: Sources.list dest: /root/Sources.list



How to Copy a file to a remote machine from a remote location?
Below is the YAML file to copy the file to remote machine path from remote machine location
--- - hosts: web tasks: - name: Copy file from one directory to other on the Remote Machine copy: src: /etc/passwd dest: /tmp/passwd remote_src: yes


How to Add one line file using Ansible?
Below is the YAML file to add one line using Ansible
--- - hosts: web tasks: - name: line insert lineinfile: path: /root/Test_Ansible.txt line: 'Add New Line 1' insertbefore: BOF










How to Add Multiple Lines in an existing file using Ansible?
Below is the YAML file to add multiple lines using Ansible 
--- - hosts: web tasks: - name: Add lines in fie lineinfile: path: /root/Test_Ansible.txt state: present line: "{{ item }}" with_items: - 'This is Line 2' - 'This is Line 3'

How to Remove Line from the existing file using Ansible?
Below is the YAML file to remove a line from Ansible
--- - hosts: web tasks: - name: Remove Line lineinfile: path: /root/Test_Ansible.txt state: absent line: 'This is Line 2'

Thursday, April 1, 2021

Add Yum Repository using Ansible

Description:  Here I have explained, How to add Yum repository using Ansible

Procedure:

  • Create YAML file and paste below content for EPEL repository

--- - hosts: all tasks: - name: Add repository yum_repository: name: epel description: EPEL YUM repo metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch&infra=$infra&content=$contentdir gpgcheck: yes gpgkey: file:///etc/pki/gpg-key
  • In the above example, I have used the EPEL repository 
  • Run YAML file using the ansible-playbook command

    # ansible-playbook repo.yaml










  • Verify  repository on the client machine 

Wednesday, March 31, 2021

Ansible Vault

 Description: Here I have explained, What is Ansible Vault, How to create Ansible Secrets on Playbook to secure them. 

What is Ansible Vault?

Ansible may need access to sensitive data such as passwords or API keys in order to configure managed hosts. Normally, this information might be stored as plain text in inventory variables or other Ansible files. Ansible Vault, which is included with Ansible, can be used to encrypt and decrypt any structured data file used by Ansible.

How to Manage Sensitive data in  Ansible Playbook?

  • First, create Ansible Secret on playbook using ansible-vault create command
          # ansible-vault create webserver.yaml
  • It will be prompted for a password for playbook 



  • Once you enter the password it open yaml playbook file, Fill require content, and save it
  • To test playbook, try to open yaml file using cat command you will data in encrypted format as follow



  • To edit the playbook, we need to use ansible-vault edit option as follow

    # ansible-vault edit webserver1.yaml

    It is a pop-up for the password for ansible-vault which we created during file creation




  • To Run playbook, use --ask-vault-pass to run with vault


Saturday, March 27, 2021

Ansible Variable

Description: Here I have explained, what is Ansible Variable and how to use Variable in the playbook

What is Ansible Variable
Ansible supports variables that can be used to store values that can then be reused throughout files in an Ansible project. This can simplify the creation and maintenance of a project and reduce 
the number of errors

Example: Here I have created a playbook to install different services and start them using variables. Below is the playbook for the same

In this example I have created below variables
    web_pkg: httpd firewall_pkg: firewalld web_service: httpd firewall_service: firewalld service python_pkg: python3-PyMySQL rule: http

--- - name: Deploy and start Apache HTTPD service hosts: webserver vars: web_pkg: httpd firewall_pkg: firewalld web_service: httpd firewall_service: firewalld rule: http tasks: - name: Required packages are installed and up to date yum: name: - "{{ web_pkg }}" - "{{ firewall_pkg }}" state: latest - name: The {{ firewall_service }} service is started and enabled service: name: "{{ firewall_service }}" enabled: true state: started - name: The {{ web_service }} service is started and enabled service: name: "{{ web_service }}" enabled: true state: started - name: Web content is in place copy: content: "This is test Webserver" dest: /var/www/html/index.html - name: The firewall port for {{ rule }} is open firewalld: service: "{{ rule }}" permanent: true immediate: true state: enabled - name: Verify the Apache service hosts: localhost become: false tasks: - name: Ensure the webserver is reachable uri: url: http://testwebserver.local status_code: 200


  • Now run playbook using below command
          # ansible-playbook webserver.yaml
  • You will get output as follow


  • You can also browse URL and verify 

Monday, December 28, 2020

How to create EC2 instance using Ansible

Description: Here I have explained, How to create EC2 instance using Ansible

Create an IAM user  from AWS console

  • Open AWS console and navigate to IAM service 


Install Require Packages on Ansible Machine

  • Once User created successfully install below require things on Ansible machine 
Ansible

# yum install ansible -y

Python 

# yum install python python-devel python-pip

Boto [Boto is the python package which provides the interface to AWS] install using pip

#  pip install boto


Create Ansible Playbook to Create EC2 instance

  • Add localhost in ansible host file for creating the connection to AWS console

[webserver]
localhost


  • Create SSH Key for localhost and copy to authorization
    # ssh-keygen -t rsa


  • Once key file created copy to authorized_keys and paste as follow
  • Create a playbook for EC2 instance and paste below content in yaml file 
# vi ec2.yaml

---
  - name: Launching the AMS instance
    hosts: localhost
    tasks:
      - name: Launching the AMS instance
        ec2:
          key_name: ansible
          region: us-east-1
  instance_type: t2.micro
  image: ami-0c582118883b46f4f
          group: Ansible
  count: 2
  aws_access_key: WODAJGU3OHZ7RDKG4TPQ
  aws_secret_key: OD3I2mgh/ynyrJJ9Y/bLQto6JLII3gyGBFYJ+w7

  Description of Playbook 
    key_name: Key created in EC2  instance 
    region: The region on which you want to create new instance
    instance_type : Instance Type in EC2 
    image: Image you want to use to create new instance, You can get image id from EC2 launch                             console

   group: Security Group name which you want to place for VM
   count : Number of EC2 instance which you want to create
   aws_access_key: Access key from the user IAM user which we have created on beginning
   aws_secret_key: Secret key from the IAM user 

  • You will get both the keys from AWS IAM console

  • Test playbook content using below command 
# ansible-playbook -C ec2.yaml


  • Once result showing OK you can run playbook using the ansible-playbook command 

# ansible-playbook ec2.yaml


  • You can see new 2 new instances on the list as follow