Giter VIP home page Giter VIP logo

azure-ssh-config's Introduction

Azure SSH Config (azuresshconfig)

Generate SSH config file from Azure ARM VM inventry in subscription

Introduction

azuresshconfig is a simple script that collects Azure ARM Virtual Machine(VM) inventry in subscription and generate a SSH config entries to be appended to $HOME/.ssh/config (the file is newly created if no exist). This is like an Azure version of ec2ssh or aws-ssh-config that strongly inspired this initiative. This would be very helpful when you manage lots of VMs that have dynamic IP assignment settings and need frequent VM up-and-down operations for them which causes the change of IPs assigned to VMs. In such a case, azuresshconfig will definitly make your SSH life easy.

Installation

pip install azuresshconfig

Configuration

Generate client profile template file by executing the following command.

azuresshconfig --init

Configure the client profile file, in which you add your service principal account info to access your resources in Azure via Azure APIs.

vi $HOME/.azure/azuresshconfig.json

{
    "subscription_id": "<YOUR SUBSCRIPTION ID>",
    "client_id": "<YOUR APPLICATION CLIENT IP>",
    "client_scret": "<YOUR APPLICATION CLIENT SCRET>",
    "tenant_id": "<YOUR TENANT ID>"
}

For those who don't know how to create service principal, there is a great instruction: Use Azure CLI to create a service principal to access resources. If you have Azure CLI 2.0 command installed on your evironment, you can create your service principal and configure its access to your azure resources with a single command 'az ad sp create-for-rbac'.

Suppose your app id uri is 'http://unofficialism.info' and role you want to give for the app is 'Reader', you can create your service principal like this:

az ad sp create-for-rbac -n "http://unofficialism.info" --role reader

You will get an output like this, and with them you can fill out the client profile file:

{
  "appId": "c36x4b4f-bef6-422e-bd3b-65057e7ab065",        # -> client_id in client profile file
  "displayName": "azure-cli-2017-03-30-05-16-59",         
  "name": "http://unofficialism.info",
  "password": "32126d32-7453-4053-3353-c420d4ffef2e",     # -> client_scret in client profile file
  "tenant": "72f988bf-86f1-41af-91cb-2d7cd011db47"        # -> tenant_id in client profile file
}

For the detail of service principal role, please refer to Built-in roles for Azure Role-Based Access Control.

Usage

Assuming all required packages are installed and rightly configured, you're ready to run azuresshconfig

azuresshconfig --help

usage: azuresshconfig.py [-h] [--version] [--init] [--profile PROFILE]
                         [--output OUTPUT] [--user USER]
                         [--identityfile IDENTITYFILE] [--private]
                         [--resourcegroups RESOURCEGROUPS] [--params PARAMS]

This program generates SSH config from Azure ARM VM inventry in subscription

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  --init                Create template client profile at
                        $HOME/.azure/azuresshconfig.json only if there is no
                        existing one
  --profile PROFILE     Specify azure client profile file to use
                        ($HOME/.azure/azuresshconfig.json by default)
  --output OUTPUT       Specify ssh config file path ($HOME/.ssh/config by
                        default). Or specify "stdout" if you want to print its
                        output to STDOUT
  --user USER           SSH username to use for all hosts
  --identityfile IDENTITYFILE
                        SSH identity file to use for all hosts
  --private             Use private IP addresses (Public IP is used by
                        default)
  --resourcegroups RESOURCEGROUPS
                        A comma-separated list of resource group to be
                        considered for ssh-config generation (all resource
                        groups by default)
  --params PARAMS       Any ssh-config params you want to add with query-
                        string format: key1=value1&key2=value2&...

1. Running with no optional args

azuresshconfig

Each host entry in output ssh-config file is simple like this:

cat ~/.ssh/config

### AZURE-SSH-CONFIG BEGIN ###

Host myvm1
    HostName 40.74.124.30

Host myvm2
    HostName 40.74.116.134
....

### AZURE-SSH-CONFIG END ###

2. Running with user, output, and identity file options

azuresshconfig --user yoichika --output /mypath/config --identityfile ~/.ssh/id_rsa

User and identify file are added to each host entry in output ssh-config file:

cat /mypath/config

### AZURE-SSH-CONFIG BEGIN ###

Host myvm1
    HostName 40.74.124.30
    IdentityFile ~/.ssh/id_rsa
    User yoichika

Host myvm2
    HostName 40.74.116.134
    IdentityFile ~/.ssh/id_rsa
    User yoichika
....

### AZURE-SSH-CONFIG END ###

3. Running with user, identity file, and resource group options

azuresshconfig --user yoichika \
                --identityfile ~/.ssh/id_rsa \
                --resourcegroups mygroup1,mygroup2

Only host entry that belong to specified resource group are added in ssh-config

4. Running with user, identity file, and additional ssh-config params

azuresshconfig.py --user yoichika \
                --identityfile ~/.ssh/id_rsa \
                --params "Port=2222&Protocol=2&UserKnownHostsFile=~/.ssh/known_hosts&ForwardAgent=yes"

Additional ssh-config params specified by --params are added to an output ssh-config file like this:

cat ~/.ssh/config

### AZURE-SSH-CONFIG BEGIN ###

Host myvm1
    HostName 40.74.124.30
    IdentityFile ~/.ssh/id_rsa
    User yoichika
    Port 2222
    Protocol 2
    UserKnownHostsFile ~/.ssh/known_hosts
    ForwardAgent yes

Host myvm2
    HostName 40.74.116.134
    IdentityFile /home/yoichika/.ssh/id_rsa
    User yoichika
    Port 2222
    Protocol 2
    UserKnownHostsFile ~/.ssh/known_hosts
    ForwardAgent yes
....

### AZURE-SSH-CONFIG END ###

Docker (Dockerfile)

Now docker image for azuresshconfig is available (yoichikawasaki/azuresshconfig). The image is based on Alpine Linux image, and contains Python2.7, pip, azuresshconfig Python packages and its prerequisite libraries.

Download size of this image is only 155 MB

$ docker images azuresshconfig
REPOSITORY                          TAG                 IMAGE ID            CREATED             SIZE
azuresshconfig                     latest              7488bef4343f        7 minutes ago       155 MB

Usage Example

$ docker run -v $HOME:/root --rm -it yoichikawasaki/azuresshconfig \
    --output stdout --user yoichika --identityfile ~/.ssh/id_rsa > $HOME/.ssh/config

or you can build from Dockerfile and run your local images like this:

$ docker build -t azuresshconfig .
$ docker run -v $HOME:/root --rm -it azuresshconfig \
     --output stdout --user yoichika --identityfile ~/.ssh/id_rsa > $HOME/.ssh/config

Shell Completion

Bash

Bash completion will work by loading bash/azuresshconfig_completion.bash. In order to load azuresshconfig_completion.bash, you can do like this

# copy this under either of following directories
cp azuresshconfig_completion.bash (/etc/bash_completion.d | /usr/local/etc/bash_completion.d | ~/bash_completion.d)

# or append 'source /path/to/azuresshconfig_completion.bash' to .bashrc like this
echo 'source /path/to/azuresshconfig_completion.bash' >> .bashrc

Once azuresshconfig_completion.bash is loaded, Bash completion will work this:

$ azuresshconfig -[tab]
-h                --identityfile    --params          --profile         --user
--help            --init            --private         --resourcegroups

$ azuresshconfig --i[tab]
--identityfile  --init

$ azuresshconfig --p[tab]
--params   --private  --profile

$ azuresshconfig --user [tab]
$ azuresshconfig --user <ssh_user>
$ azuresshconfig --user <ssh_user> --identityfile [tab]
$ azuresshconfig --user <ssh_user> --identityfile <ssh_identity_file>

Todo

  • Support zsh Completion (Hopefully support it soon)

Issues

Change log

Links

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/yokawasa/azure-ssh-config.

Copyright

CopyrightCopyright (c) 2016- Yoichi Kawasaki
LicenseMIT

azure-ssh-config's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

azure-ssh-config's Issues

Bug: Duplicate HostName definitions showed for each host entry

it's like this:

Host testhost1
    HostName 40.74.242.61
    HostName 40.74.242.61 <<<< duplicated
    IdentityFile /home/yoichika/.ssh/id_rsa
    User yoichika

Host testhost2
    HostName 40.72.124.30
    HostName 40.72.124.30 <<<< duplicated
    IdentityFile /home/yoichika/.ssh/id_rsa
    User yoichika

Request: Add ssh-config file options

Now ssh-config is $HOME/.ssh/config by default and you can't change the path. This is a request to add ssh-config file path option so that you can change the path accordingly

TypeError: Parameter 'subscription_id'

Got the following error message and the command execution failed even if subscription_id value is actually assigned as string

$ ./azuresshconfig.py
Traceback (most recent call last):
File "./azuresshconfig.py", line 341, in
main()
File "./azuresshconfig.py", line 293, in main
credentials, cconf.subscription_id)
File "/usr/local/lib/python2.7/dist-packages/azure/mgmt/compute/compute_management_client.py", line 132, in init
self.config = ComputeManagementClientConfiguration(credentials, subscription_id, accept_language, long_running_operation_retry_timeout, generate_client_request_id, base_url, fi
lepath)
File "/usr/local/lib/python2.7/dist-packages/azure/mgmt/compute/compute_management_client.py", line 63, in init
raise TypeError("Parameter 'subscription_id' must be str.")
TypeError: Parameter 'subscription_id' must be str.

Support Python3.X

Obviously azure-ssh-config doesn't support Python3.X

$ python --version
Python 3.5.0
$ ./azuresshconfig.py --h
  File "./azuresshconfig.py", line 352
    print "{}".format(ssh_config_block)
             ^
SyntaxError: invalid syntax

Error occur when VM doesn't have Public IP Address

The following error occurs when VM doesn't have Public IP Address

Traceback (most recent call last):
  File "/usr/local/bin/azuresshconfig", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/azuresshconfig.py", line 314, in main
    ni_info = get_network_interface_info(network_client, ni.id)
  File "/usr/local/lib/python2.7/dist-packages/azuresshconfig.py", line 217, in get_network_interface_info
    public_address_id = ipconfig.public_ip_address.id
AttributeError: 'NoneType' object has no attribute 'id'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.