ec2_key 5.09 KB
Newer Older
Vincent Viallet committed
1 2 3 4 5 6 7
#!/usr/bin/python
# -*- coding: utf-8 -*-


DOCUMENTATION = '''
---
module: ec2_key
Vincent Viallet committed
8
version_added: "1.5"
Vincent Viallet committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
short_description: maintain an ec2 key pair.
description:
    - maintains ec2 key pairs. This module has a dependency on python-boto >= 2.5
options:
  name:
    description:
      - Name of the key pair.
    required: true
  key_material:
    description:
      - Public key material.
    required: false
  region:
    description:
      - the EC2 region to use
    required: false
    default: null
    aliases: []
  ec2_url:
    description:
      - Url to use to connect to EC2 or your Eucalyptus cloud (by default the module will use EC2 endpoints)
    required: false
    default: null
    aliases: []
  ec2_secret_key:
    description:
      - EC2 secret key
    required: false
    default: null
38
    aliases: ['aws_secret_key', 'secret_key']
Vincent Viallet committed
39 40 41 42 43
  ec2_access_key:
    description:
      - EC2 access key
    required: false
    default: null
44
    aliases: ['aws_access_key', 'access_key']
Vincent Viallet committed
45 46
  state:
    description:
47
      - create or delete keypair
Vincent Viallet committed
48 49 50
    required: false
    default: 'present'
    aliases: []
51 52 53 54 55 56 57 58
  validate_certs:
    description:
      - When set to "no", SSL certificates will not be validated for boto versions >= 2.6.0.
    required: false
    default: "yes"
    choices: ["yes", "no"]
    aliases: []
    version_added: "1.5"
59 60 61 62 63 64
  profile:
    description:
      - uses a boto profile. Only works with boto >= 2.24.0
    required: false
    default: null
    aliases: []
65
    version_added: "1.6"
66 67 68 69 70 71
  security_token:
    description:
      - security token to authenticate against AWS
    required: false
    default: null
    aliases: []
72
    version_added: "1.6"
Vincent Viallet committed
73 74 75 76 77 78

requirements: [ "boto" ]
author: Vincent Viallet
'''

EXAMPLES = '''
79 80 81
# Note: None of these examples set aws_access_key, aws_secret_key, or region.
# It is assumed that their matching environment variables are set.

Vincent Viallet committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
# Creates a new ec2 key pair named `example` if not present, returns generated
# private key
- name: example ec2 key
  local_action:
    module: ec2_key
    name: example

# Creates a new ec2 key pair named `example` if not present using provided key
# material
- name: example2 ec2 key
  local_action:
    module: ec2_key
    name: example2
    key_material: 'ssh-rsa AAAAxyz...== me@example.com'
    state: present

# Creates a new ec2 key pair named `example` if not present using provided key
# material
- name: example3 ec2 key
  local_action:
    module: ec2_key
    name: example3
    key_material: "{{ item }}"
  with_file: /path/to/public_key.id_rsa.pub

# Removes ec2 key pair by name
- name: remove example key
  local_action:
    module: ec2_key
    name: example
    state: absent
'''

try:
    import boto.ec2
except ImportError:
    print "failed=True msg='boto required for this module'"
    sys.exit(1)

def main():
122 123
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
Vincent Viallet committed
124 125 126
            name=dict(required=True),
            key_material=dict(required=False),
            state = dict(default='present', choices=['present', 'absent']),
127 128 129 130
        )
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
Vincent Viallet committed
131 132 133 134 135 136 137 138 139
        supports_check_mode=True,
    )

    name = module.params['name']
    state = module.params.get('state')
    key_material = module.params.get('key_material')

    changed = False

140
    ec2 = ec2_connect(module)
Vincent Viallet committed
141 142 143 144 145 146 147 148 149 150 151

    # find the key if present
    key = ec2.get_key_pair(name)

    # Ensure requested key is absent
    if state == 'absent':
        if key:
            '''found a match, delete it'''
            try:
                key.delete()
            except Exception, e:
152
                module.fail_json(msg="Unable to delete key pair '%s' - %s" % (key, e))
Vincent Viallet committed
153 154 155 156 157 158
            else:
                key = None
                changed = True
        else:
            '''no match found, no changes required'''

159
    # Ensure requested key is present
Vincent Viallet committed
160 161 162 163 164 165 166 167
    elif state == 'present':
        if key:
            '''existing key found'''
            # Should check if the fingerprint is the same - but lack of info
            # and different fingerprint provided (pub or private) depending if
            # the key has been created of imported.
            pass

168
        # if the key doesn't exist, create it now
Vincent Viallet committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        else:
            '''no match found, create it'''
            if not module.check_mode:
                if key_material:
                    '''We are providing the key, need to import'''
                    key = ec2.import_key_pair(name, key_material)
                else:
                    '''
                    No material provided, let AWS handle the key creation and 
                    retrieve the private key
                    '''
                    key = ec2.create_key_pair(name)
            changed = True

    if key:
        data = {
            'name': key.name,
            'fingerprint': key.fingerprint
        }
        if key.material:
            data.update({'private_key': key.material})

        module.exit_json(changed=changed, key=data)
    else:
        module.exit_json(changed=changed, key=None)

# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *

main()