Skip to content

Commit

Permalink
improve(ram): Add ram module
Browse files Browse the repository at this point in the history
  • Loading branch information
lixue323 committed Feb 21, 2020
1 parent 87534b3 commit eb2ec33
Show file tree
Hide file tree
Showing 31 changed files with 2,483 additions and 2 deletions.
1 change: 0 additions & 1 deletion contrib/inventory/alicloud.ini
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ group_by_security_group = True
group_by_tag_keys = True
group_by_tag_none = True


# If you only want to include hosts that match a certain regular expression
# pattern_include = myhost-*

Expand Down
2 changes: 1 addition & 1 deletion contrib/inventory/alicloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def read_settings(self):
'group_by_vswitch_id',
'group_by_security_group',
'group_by_tag_keys',
'group_by_tag_none'
'group_by_tag_none',
]
for option in group_by_options:
setattr(self, option, self.get_option(config, 'ecs', option))
Expand Down
29 changes: 29 additions & 0 deletions lib/ansible/module_utils/alicloud_ecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import footmark.ess
import footmark.sts
import footmark.dns
import footmark.ram
HAS_FOOTMARK = True
except ImportError:
HAS_FOOTMARK = False
Expand Down Expand Up @@ -248,3 +249,31 @@ def ess_connect(module):
module.fail_json(msg=str(e))
# Otherwise, no region so we fallback to the old connection method
return ess


def sts_connect(module):
""" Return an sts connection"""
sts_params = get_profile(module.params)
# If we have a region specified, connect to its endpoint.
region = module.params.get('alicloud_region')
if region:
try:
sts = connect_to_acs(footmark.sts, region, **sts_params)
except AnsibleACSError as e:
module.fail_json(msg=str(e))
# Otherwise, no region so we fallback to the old connection method
return sts


def ram_connect(module):
""" Return an ram connection"""
ram_params = get_profile(module.params)
# If we have a region specified, connect to its endpoint.
region = module.params.get('alicloud_region')
if region:
try:
ram = connect_to_acs(footmark.ram, region, **ram_params)
except AnsibleACSError as e:
module.fail_json(msg=str(e))
# Otherwise, no region so we fallback to the old connection method
return ram
185 changes: 185 additions & 0 deletions lib/ansible/modules/cloud/alicloud/ali_ram_access_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
#!/usr/bin/python
# Copyright (c) 2017-present Alibaba Group Holding Limited. He Guimin <heguimin36@163.com.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# 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/.


__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}

DOCUMENTATION = """
---
module: ali_ram_access_key
version_added: "2.9"
short_description: Create, Delete, Update Ram Access Key in Alibaba Cloud.
description:
- Create, Delete Ram Access Key and Update status in Alibaba Cloud.
- This module does not support idempotence
options:
state:
description:
- If I(state=present), access key will be created.
- If I(state=present) and user_access_key_id exists, access key will be updated.
- If I(state=absent), access key will be removed.
choices: ['present', 'absent']
default: 'present'
user_name:
description:
- The username of the RAM user.
required: True
user_access_key_id:
description:
- The ID of the AccessKey to be updated. Required when update access key.
status:
description:
- The status of the AccessKey. Required when update access key.
choices: ['Active', 'Inactive']
requirements:
- "python >= 3.6"
- "footmark >= 1.17.0"
extends_documentation_fragment:
- alicloud
author:
- "He Guimin (@xiaozhu36)"
"""

EXAMPLES = """
# Note: These examples do not set authentication details, see the Alibaba Cloud Guide for details.
- name: Changed. Create access key
ali_ram_access_key:
user_name: ansible
register: access
- name: Changed. Update access key
ali_ram_access_key:
user_access_key_id: '{{ user_access_key_id }}'
user_name: ansible
status: Inactive
- name: Changed. Delete access key
ali_ram_access_key:
state: absent
user_access_key_id: '{{ user_access_key_id }}'
user_name: ansible
"""

RETURN = '''
user:
description: Returns an array of complex objects as described below.
returned: always
type: complex
contains:
access_key_id:
description: The AccessKeyId.
returned: always
type: string
sample: 0wNEpMMlzy7s****
access_key_secret:
description: The AccessKeySecret.
returned: When create access key
type: string
sample: PupkTg8jdmau1cXxYacgE736PJ****
create_date:
description: The date and time when the AccessKey was created.
returned: always
type: string
sample: 2015-01-23T12:33:18Z
status:
description: The status of the AccessKey.
returned: always
type: string
sample: Active
'''

import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.alicloud_ecs import ecs_argument_spec, ram_connect

HAS_FOOTMARK = False

try:
from footmark.exception import RAMResponseError
HAS_FOOTMARK = True
except ImportError:
HAS_FOOTMARK = False


def list_access_key(module, ram_conn, user_name):
try:
res = []
exists = ram_conn.list_access_keys(user_name=user_name)
if exists:
for ak in exists:
res.append(ak.read())
return res
except Exception as e:
module.fail_json(msg="Failed to get profile: {0}".format(e))


def main():
argument_spec = ecs_argument_spec()
argument_spec.update(dict(
state=dict(default='present', choices=['present', 'absent']),
user_name=dict(type='str', required=True, aliases=['name']),
user_access_key_id=dict(type='str'),
status=dict(type='str', choices=['Active', 'Inactive'])
))

module = AnsibleModule(argument_spec=argument_spec)

if HAS_FOOTMARK is False:
module.fail_json(msg='footmark required for this module.')

ram_conn = ram_connect(module)

# Get values of variable
state = module.params['state']
user_access_key_id = module.params['user_access_key_id']
user_name = module.params['user_name']
aks = list_access_key(module, ram_conn, user_name)

changed = False

if state == 'absent':
try:
module.exit_json(changed=ram_conn.delete_access_key(**module.params), access_key={})
except RAMResponseError as e:
module.fail_json(msg='Unable to delete access_key, error: {}'.format(e))

if user_access_key_id:
try:
res = ram_conn.update_access_key(**module.params)
if res:
module.exit_json(changed=True, access_key=res.read())
module.exit_json(changed=changed, access_key={})
except Exception as e:
module.fail_json(msg='Unable to update access_key, error: {}'.format(e))
if len(aks) < 2:
try:
access_key = ram_conn.create_access_key(**module.params)
module.exit_json(changed=True, access_key=access_key.read())
except RAMResponseError as e:
module.fail_json(msg='Unable to create access_key, error: {0}'.format(e))

module.exit_json(changed=changed, access_key=aks)


if __name__ == '__main__':
main()
116 changes: 116 additions & 0 deletions lib/ansible/modules/cloud/alicloud/ali_ram_access_key_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#!/usr/bin/python
# Copyright (c) 2017-present Alibaba Group Holding Limited. He Guimin <heguimin36@163.com.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# 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/.


__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}

DOCUMENTATION = '''
---
module: ali_ram_access_key_info
version_added: "2.9"
short_description: List the AccessKeys of a RAM user in Alibaba Cloud.
description:
- List the AccessKeys of a RAM user.
options:
user_name:
description:
- The username of the RAM user. If this parameter is not set when the user logs on to the console,
the AccessKeys of this user are displayed.
author:
- "He Guimin (@xiaozhu36)"
requirements:
- "python >= 3.6"
- "footmark >= 1.17.0"
extends_documentation_fragment:
- alicloud
'''

EXAMPLES = '''
# Note: These examples do not set authentication details, see the Alibaba Cloud Guide for details.
- name: Get infos about all Users
ali_ram_user_info:
- name: Get infos about a particular User using name_prefix
ali_ram_user_info:
name_prefix: "ansible"
'''

RETURN = '''
users:
description: Returns an array of complex objects as described below.
returned: always
type: list
sample:[
{
access_key_id:
description: The AccessKeyId.
returned: always
type: string
sample: 0wNEpMMlzy7s****
create_date:
description: The date and time when the AccessKey was created.
returned: always
type: string
sample: 2015-01-23T12:33:18Z
status:
description: The status of the AccessKey.
returned: always
type: string
sample: Active
}
]
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.alicloud_ecs import ecs_argument_spec, ram_connect

HAS_FOOTMARK = False

try:
from footmark.exception import RAMResponseError
HAS_FOOTMARK = True
except ImportError:
HAS_FOOTMARK = False


def main():
argument_spec = ecs_argument_spec()
argument_spec.update(dict(
user_name=dict(type='str'), aliases=['name'])
)
module = AnsibleModule(argument_spec=argument_spec)

if HAS_FOOTMARK is False:
module.fail_json(msg="Package 'footmark' required for this module.")
try:
access_key = []
for access in ram_connect(module).list_access_keys(**module.params):
access_key.append(access.read())
module.exit_json(changed=False, access_keys=access_key)
except Exception as e:
module.fail_json(msg=str("Unable to list access_keys, error:{0}".format(e)))


if __name__ == '__main__':
main()
Loading

0 comments on commit eb2ec33

Please sign in to comment.