Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Ansible




yum install epel-release
yum update
     ////////   yum install -y gcc
      /////////  yum install -y python-setuptools
     /////////    sudo easy_install pip
     //////    sudo yum install python-devel
   ///////      sudo pip install ansible
////////sudo  install ansible

######copy ansible folder /home/uploads/

#####if copied ansible >root#]ansible-playbook  web.bo.base.col.myg.net.yml -i /home/uploads/ansible/hosts

###########simple playbook############
yum install ansible -y

---------------------------------------
/etc/ansible/web_db.yml
---------------------------------------
---
- hosts: webservers:dbservers
  sudo: yes

  tasks:
  - name: Ensure that apache is installed
    yum: name=httpd state=present    ###present=if installed , not going to installed

  - name: Start Apache services
    service: name=httpd enabled=yes state=started

- hosts: dbservers
  sudo: yes

  tasks:
  - name: Ensure mysql installed
    yum: name=mysql-server state=present
  - name: Start Mysql
    service: name=mysqld state=started

- hosts: webservers:dbservers
  sudo: yes

  tasks:
  - name: Stop IP tables now!!
    service: name=iptables state=stopped
---------------------------------------
vim /etc/ansible/hosts
[webservers]
192.168.137.11

[dbservers]
192.168.137.12
----------------------------------------
ansible-playbook web_db.yml

#####copy and replace########
---
- hosts: webservers
  sudo: yes

  tasks:
  - name: replace work hello to hi
    replace:
     dest=/etc/foo.txt
     regexp='hi'
     replace='hello'
     backup=yes
###########################

JDK

first make downloadable file in some server mine its in ansible server (137.20)
Alias /downloads /downloads/
<Directory "/downloads/">
    #Options None
    Options Indexes
    AllowOverride None
    Order allow,deny
    Allow from all
#    AuthName "Download Rates File Access"
#    AuthType Basic
#    AuthUserFile /mysystem/downloadratesaccess/htpasswd.hotelstaticdata
#    Require valid-user
</Directory>

ansible/jdk_install.yml
---
 - hosts: server1
   gather_facts: yes
   remote_user: root
   become: yes
   become_method: sudo

   roles:
    - { role: jdk,
      jdk_version: jdk1.5.0_22,  #jdk1.6.0_37, jdk1.7.0_79 ## overites var location
      jdk_archive_file: jdk1.5.0_22.zip #jdk1.6.0_37.tar.gz, jdk1.7.0_79.tar.gz
      }

    - { role: jboss,
       jboss_node: jboss_2,
       jboss_file: jboss_2,
       jboss_zip: jboss_2.zip
      }


/etc/ansible/roles/jdk/handlers/main.yml
---
- name: source bashrc

  shell: source /etc/bashrc


/etc/ansible/roles/jdk/vars/main.yml
---
downloads_directory: /home/myuser/software
jdk_directory: /usr/java
downloads_url: //192.168.137.20/downloads/
jdk_version: jdk1.5.0_22
jdk_archive_file: jdk1.5.0_22.zip


/etc/ansible/roles/jdk/tasks/main.yml
---
- name: Check if java version exists
  stat: path={{jdk_directory}}/{{jdk_version}}/bin/java
  register: java_avail

- name: Create java directory
  file: path={{jdk_directory}} state=directory mode=775

- name: Create download directory
  file: path={{downloads_directory}} state=directory mode=775

- name: Download Java JDK
  get_url:
    url=http:{{downloads_url}}{{jdk_archive_file}}
    dest={{downloads_directory}}/
  when: java_avail.stat.exists == false

- name: Extract JDK
  unarchive: src={{downloads_directory}}/{{jdk_archive_file}} dest={{jdk_directory}} copy=no
  when: java_avail.stat.exists == false


- name: Create symlink for jdk
  file: src={{jdk_directory}}/{{jdk_version}} dest={{jdk_directory}}/jdk state=link
  when: java_avail.stat.exists == false

- name: Create Jboss executable
  command: cp {{item.src}} {{item.dest}}
    creates={{item.creates}}
    chdir={{jdk_directory}}/{{jdk_version}}/bin/
  with_items:
    - {src: java, dest: java_n1, creates: java_n1}
    - {src: java, dest: java_n2, creates: java_n2}
    - {src: java, dest: java_n3, creates: java_n3}
    - {src: java, dest: java_n4, creates: java_n4}



- name: Append JAVA_HOME to bashrc
  lineinfile:
    dest=/etc/bashrc
    line='{{item}}'
  with_items:
    - export JAVA_HOME=/usr/java/jdk
    - export PATH=$JAVA_HOME/bin:$PATH
  notify: source bashrc

#- name: Ensure files are 0775
#  command: find {{ jdk_directory }} -type f -exec chmod 0775 {} \;



########################################

roles/jboss/vars/main.yml 
---
downloads_url: http://192.168.137.20/downloads

jboss_destination_path: /mysystem/jboss
script_destination_path: /mysystem/myadmin
jboss_zip: jboss_1.zip
jboss_file: jboss_1
jboss_bind: 1099
portalStaicData_zip: portalstaticdata.zip
portalStaicData_path: /mysystem/


jboss_node: jboss_1

roles/jboss/tasks/main.yml
---
- name: Create Jboss folder
  file:
    path={{jboss_destination_path}}
    state=directory
    mode=0775
    owner=myuser
    group=myuser

- name: Create mygadmin folder
  file:
    path={{script_destination_path}}
    state=directory
    mode=0775
    owner=myuser
    group=myuser

- name: Jboss Install
  include: install_jboss.yml


- name: Append Scripts to bashrc
  lineinfile:
    dest=/etc/bashrc
    line='{{item}}'
  with_items:
    - export PATH={{script_destination_path}}:$PATH
  notify: source bashrc


roles/jboss/tasks/install_jboss.yml
---
- name: Check Jboss existance
  stat: path={{jboss_destination_path}}/{{jboss_node}}/server/default/conf/log4j.xml
  register: jboss_avail

- name: Download Jboss
  get_url:
    url={{downloads_url}}/{{jboss_node}}.zip
    dest={{jboss_destination_path}}
    mode=0775
    owner=myuser
    group=myuser
  when: jboss_avail.stat.exists == false

- name: Extract Jboss
  unarchive:
    src={{jboss_destination_path}}/{{jboss_node}}.zip
    dest={{jboss_destination_path}}
    copy=no
    mode=0775
    owner=myuser
    group=myuser
  when: jboss_avail.stat.exists == false



- name: Download Scripts jbstart
  get_url:
    url={{downloads_url}}/{{jboss_node}}start
    dest={{script_destination_path}}
    mode=0775
    owner=myuser
    group=myuser

- name: Download Scripts jbstop
  get_url:
    url={{downloads_url}}/{{jboss_node}}stop
    dest={{script_destination_path}}
    mode=0775
    owner=myuser
    group=myuser

- name: Download PortalStaicData
  get_url:
    url={{downloads_url}}/{{portalStaicData_zip}}
    dest={{portalStaicData_path}}
    mode=0775
    owner=myuser
    group=myuser

- name: Extract PortalStaicData
  unarchive:
    src={{portalStaicData_path}}/{{portalStaicData_zip}}
    dest={{portalStaicData_path}}
    copy=no

- name: Delete Jboss compressed file after extracting it
  file:
    path={{jboss_destination_path}}/{{jboss_zip}}
    state=absent
  when: jboss_avail.stat.exists == false

- name: Delete Portal Staic data  after extracting it
  file:
    path={{portalStaicData_path}}/{{portalStaicData_zip}}
    state=absent

#- name: Download PersistenceConfig
#  get_url:
#    url={{download_url_84}}/{{persistenceConfig_zip}}
#    dest={{persistenceConfig_path}}
#    mode=0775
#    owner=myuser
#    group=myuser

#- name: Extract PersistenceConfig
#  unarchive:
#    src={{persistenceConfig_path}}/{{persistenceConfig_zip}}
#    dest={{persistenceConfig_path}}
#    copy=no



#- name: Delete PersistenceConfig data  after extracting it
#  file:
#    path={{persistenceConfig_path}}/{{persistenceConfig_zip}}
#    state=absent
                                         


-----------------------
run ansible using another user
host ] vi /etc/sudoers  -> myadmin ALL=(ALL)       NOPASSWD:ALL

ansi server]  ssh-copy-id myadmin@hostip
-----------------------


TERRAFORM
download - >https://www.terraform.io/downloads.html
unzip to /opt/teraform (whatever location )
vim etc/bashrc -> add /opt/ path
verify --> terraform
-
mkdir /digi/ (whatever)
cd /digi/










vim provider.tf
provider "digitalocean" {

  token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

}


vim www-1.tf
resource "digitalocean_droplet" "www-1" {
    image = "ubuntu-14-04-x64"
    name = "www-1"
    region = "nyc2"
    size = "512mb"
    private_networking = true
    ssh_keys = [
"23:ey:3g:bf:9e:24:4c:84:b7:4b:c5:4f:a0:5c:4d:4c"
]
}

Note : copy your local pc's /root/.ssh/id_rsa.pub and paste in digitalocn

copy that fingerprint and paste it in above ssh_keys block (or use -> ssh-keygen -lf /root/.ssh/id_rsa.pub | awk '{print $2}' to get that finger print )

finally,
terraform plan
terraform apply







======================================
RACKSPACE PYRAX (Creating dynamic inventory )

 yum -y update
 yum -y install python-setuptools python-devel vim sshpass gcc
 easy_install pip
            #make sure it is up to date
            pip install pip --upgrade

easy_install distribute
pip install --upgrade distribute

pip install six distribute --upgrade


yum install openssl-devel
pip install pyrax

==============================================
vim /root/.rackspace_cloud_credentials
            [rackspace_cloud]
            username = my_username
            api_key = 01234567890abcdef


==============================================
vim /home/uploads/test_inventory.py

##########Change only this when required --->cs = pyrax.connect_to_cloudservers(region="IAD") / ex: DFW, ORD, IAD, LON
##### Some time you may need to edit this also -->cs = pyrax.connect_to_cloudservers(region=region)  ---> ---(region="IAD")

#!/usr/bin/env python

# (c) 2013, Jesse Keating <jesse.keating@rackspace.com>
#
# This file is part of Ansible,
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION = '''

---
inventory: rax
short_description: Rackspace Public Cloud external inventory script
description:
  - Generates inventory that Ansible can understand by making API request to Rackspace Public Cloud API
  - |
    When run against a specific host, this script returns the following variables:
        rax_os-ext-sts_task_state
        rax_addresses
        rax_links
        rax_image
        rax_os-ext-sts_vm_state
        rax_flavor
        rax_id
        rax_rax-bandwidth_bandwidth
        rax_user_id
        rax_os-dcf_diskconfig
        rax_accessipv4
        rax_accessipv6
        rax_progress
        rax_os-ext-sts_power_state
        rax_metadata
        rax_status
        rax_updated
        rax_hostid
        rax_name
        rax_created
        rax_tenant_id
        rax_loaded
    where some item can have nested structure.
  - credentials are set in a credentials file
version_added: None
options:
  creds_file:
    description:
     - File to find the Rackspace Public Cloud credentials in
    required: true
    default: null
  region:
    description:
     - An optional value to narrow inventory scope, i.e. DFW, ORD, IAD, LON
     required: false
     default: null
authors:
  - Jesse Keating <jesse.keating@rackspace.com>
  - Paul Durivage <paul.durivage@rackspace.com>
notes:
  - RAX_CREDS_FILE is an optional environment variable that points to a pyrax-compatible credentials file.
  - If RAX_CREDS_FILE is not supplied, rax.py will look for a credentials file at ~/.rackspace_cloud_credentials.
  - See https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md#authenticating
  - RAX_REGION is an optional environment variable to narrow inventory search scope
  - RAX_REGION, if used, needs a value like ORD, DFW, SYD (a Rackspace datacenter) and optionally accepts a comma-separated list
requirements: [ "pyrax" ]
examples:
    - description: List server instances
      code: RAX_CREDS_FILE=~/.raxpub rax.py --list
    - description: List servers in ORD datacenter only
      code: RAX_CREDS_FILE=~/.raxpub RAX_REGION=ORD rax.py --list
    - description: List servers in ORD and DFW datacenters
      code: RAX_CREDS_FILE=~/.raxpub RAX_REGION=ORD,DFW rax.py --list
    - description: Get server details for server named "server.example.com"
      code: RAX_CREDS_FILE=~/.raxpub rax.py --host server.example.com
'''

import sys
import re
import os

import argparse
import collections

try:
    import json
except:
    import simplejson as json

try:
    import pyrax
except ImportError:
    print('pyrax required for this module')
    sys.exit(1)


def host(regions, hostname):
    hostvars = {}

    for region in regions:
        # Connect to the region
        cs = pyrax.connect_to_cloudservers(region="IAD")
        for server in cs.servers.list():
            if server.name == hostname:
                keys = [key for key in vars(server) if key not in ('manager', '_info')]
                for key in keys:
                    # Extract value
                    value = getattr(server, key)

                    # Generate sanitized key
                    key = 'rax_' + (re.sub("[^A-Za-z0-9\-]", "_", key)
                                      .lower()
                                      .lstrip("_"))
                    hostvars[key] = value

                # And finally, add an IP address
                hostvars['ansible_ssh_host'] = server.accessIPv4
    print(json.dumps(hostvars, sort_keys=True, indent=4))


def _list(regions):
    groups = collections.defaultdict(list)
    hostvars = collections.defaultdict(dict)

    # Go through all the regions looking for servers
    for region in regions:
        # Connect to the region
        cs = pyrax.connect_to_cloudservers(region=region)
        for server in cs.servers.list():
            # Create a group on region
            groups[region].append(server.name)

            # Check if group metadata key in servers' metadata
            try:
                group = server.metadata['group']
            except KeyError:
                pass
            else:
                # Create group if not exist and add the server
                groups[group].append(server.name)

            # Add host metadata
            keys = [key for key in vars(server) if key not in ('manager', '_info')]
            for key in keys:
                # Extract value
                value = getattr(server, key)

                # Generate sanitized key
                key = 'rax_' + (re.sub("[^A-Za-z0-9\-]", "_", key)
                                  .lower()
                                  .lstrip('_'))
                hostvars[server.name][key] = value

            # And finally, add an IP address
            hostvars[server.name]['ansible_ssh_host'] = server.accessIPv4

    if hostvars:
        groups['_meta'] = {'hostvars': hostvars}
    print(json.dumps(groups, sort_keys=True, indent=4))


def parse_args():
    parser = argparse.ArgumentParser(description='Ansible Rackspace Cloud '
                                                 'inventory module')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--list', action='store_true',
                        help='List active servers')
    group.add_argument('--host', help='List details about the specific host')
    return parser.parse_args()


def setup():
    default_creds_file = os.path.expanduser('/root/.rackspace_cloud_credentials')

    # Attempt to grab credentials from environment first
    try:
        creds_file = os.environ['RAX_CREDS_FILE']
    except KeyError, e:
        # But if that fails, use the default location of ~/.rackspace_cloud_credentials
        if os.path.isfile(default_creds_file):
            creds_file = default_creds_file
        else:
            sys.stderr.write('No value in environment variable %s and/or no '
                             'credentials file at %s\n'
                             % (e.message, default_creds_file))
            sys.exit(1)

    pyrax.set_setting('identity_type', 'rackspace')

    try:
        pyrax.set_credential_file(os.path.expanduser(creds_file))
    except Exception, e:
        sys.stderr.write("%s: %s\n" % (e, e.message))
        sys.exit(1)

    regions = []
    for region in os.getenv('RAX_REGION', 'all').split(','):
        region = region.strip().upper()
        if region == 'ALL':
            regions = pyrax.regions
            break
        elif region not in pyrax.regions:
            sys.stderr.write('Unsupported region %s' % region)
            sys.exit(1)
        elif region not in regions:
            regions.append(region)

    return regions


def main():
    args = parse_args()
    regions = setup()
    if args.list:
        _list(regions)
    elif args.host:
        host(regions, args.host)
    sys.exit(0)

if __name__ == '__main__':
    main()

                 
=====================================================
./test_inventory.py --list
(you should see the server list)
######################################

11 comments:

  1. Hello,
    Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing...
    Know More AboutAnsible Training

    ReplyDelete
  2. Appreciate your work, very informative blog on Ansible. I just wanted to share information about Ansible Online Training. Hope it helps the community here.

    ReplyDelete

  3. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.i want to share about advanced java tutorial and java advanced tutorials .

    ReplyDelete
  4. I just see the post i am so happy the post of information's.So I have really enjoyed and reading your blogs for these posts.Any way I’ll be subscribing to your feed and I hope you post again soon.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training

    ReplyDelete
  5. The Lucky Streak Casino Resort in Marrakech, MS - KTH
    Book online The Lucky Streak Casino 김포 출장마사지 Resort or your next hotel stay with 춘천 출장안마 JMT or Mohegan Sun, a premier 아산 출장마사지 resort destination 메이저 바카라 사이트 destination 충청남도 출장안마 for entertainment

    ReplyDelete