Initial commit

This commit is contained in:
Jon Ervine
2021-03-02 20:53:43 +08:00
parent 89d3a2dfe1
commit f961b728fa
2919 changed files with 388582 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import requests
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def save_playbook(self, proj_path, remediation, content):
name = remediation.get('name', None) or 'insights-remediation'
name = re.sub(r'[^\w\s-]', '', name).strip().lower()
name = re.sub(r'[-\s]+', '-', name)
fname = '{}-{}.yml'.format(name, remediation['id'])
file_path = os.path.join(proj_path, fname)
with open(file_path, 'wb') as f:
f.write(content)
def is_stale(self, proj_path, etag):
file_path = os.path.join(proj_path, '.version')
try:
with open(file_path, 'r') as f:
version = f.read()
return version != etag
except IOError:
return True
def write_version(self, proj_path, etag):
file_path = os.path.join(proj_path, '.version')
with open(file_path, 'w') as f:
f.write(etag)
def run(self, tmp=None, task_vars=None):
self._supports_check_mode = False
result = super(ActionModule, self).run(tmp, task_vars)
insights_url = self._task.args.get('insights_url', None)
username = self._task.args.get('username', None)
password = self._task.args.get('password', None)
proj_path = self._task.args.get('project_path', None)
license = self._task.args.get('awx_license_type', None)
awx_version = self._task.args.get('awx_version', None)
session = requests.Session()
session.auth = requests.auth.HTTPBasicAuth(username, password)
headers = {
'Content-Type': 'application/json',
'User-Agent': '{} {} ({})'.format(
'AWX' if license == 'open' else 'Red Hat Ansible Tower',
awx_version,
license
)
}
url = '/api/remediations/v1/remediations'
while url:
res = session.get('{}{}'.format(insights_url, url), headers=headers, timeout=120)
if res.status_code != 200:
result['failed'] = True
result['msg'] = (
'Expected {} to return a status code of 200 but returned status '
'code "{}" instead with content "{}".'.format(url, res.status_code, res.content)
)
return result
# FIXME: ETags are (maybe?) not yet supported in the new
# API, and even if they are we'll need to put some thought
# into how to deal with them in combination with pagination.
if 'ETag' in res.headers:
version = res.headers['ETag']
if version.startswith('"') and version.endswith('"'):
version = version[1:-1]
else:
version = "ETAG_NOT_FOUND"
if not self.is_stale(proj_path, version):
result['changed'] = False
result['version'] = version
return result
url = res.json()['links']['next'] # will be None if we're on the last page
for item in res.json()['data']:
playbook_url = '{}/api/remediations/v1/remediations/{}/playbook'.format(
insights_url, item['id'])
res = session.get(playbook_url, timeout=120)
if res.status_code == 204:
continue
elif res.status_code != 200:
result['failed'] = True
result['msg'] = (
'Expected {} to return a status code of 200 but returned status '
'code "{}" instead with content "{}".'.format(
playbook_url, res.status_code, res.content)
)
return result
self.save_playbook(proj_path, item, res.content)
self.write_version(proj_path, version)
result['changed'] = True
result['version'] = version
return result
@@ -0,0 +1,98 @@
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import errno
import os
import tarfile
import zipfile
from ansible.plugins.action import ActionBase
from ansible.utils.display import Display
display = Display()
try:
from zipfile import BadZipFile
except ImportError:
from zipfile import BadZipfile as BadZipFile # py2 compat
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
self._supports_check_mode = False
result = super(ActionModule, self).run(tmp, task_vars)
src = self._task.args.get("src")
proj_path = self._task.args.get("project_path")
force = self._task.args.get("force", False)
try:
archive = zipfile.ZipFile(src)
get_filenames = archive.namelist
get_members = archive.infolist
except BadZipFile:
try:
archive = tarfile.open(src)
except tarfile.ReadError:
result["failed"] = True
result["msg"] = "{0} is not a valid archive".format(src)
return result
get_filenames = archive.getnames
get_members = archive.getmembers
# Most well formed archives contain a single root directory, typically named
# project-name-1.0.0. The project contents should be inside that directory.
start_index = 0
root_contents = set(
[filename.split(os.path.sep)[0] for filename in get_filenames()]
)
if len(root_contents) == 1:
start_index = len(list(root_contents)[0]) + 1
for member in get_members():
try:
filename = member.filename
except AttributeError:
filename = member.name
# Skip the archive base directory
if not filename[start_index:]:
continue
dest = os.path.join(proj_path, filename[start_index:])
if not force and os.path.exists(dest):
continue
try:
is_dir = member.is_dir()
except AttributeError:
try:
is_dir = member.isdir()
except AttributeError:
is_dir = member.filename[-1] == '/' # py2 compat for ZipInfo
if is_dir:
try:
os.makedirs(dest)
except OSError as exc: # Python >= 2.5
if exc.errno == errno.EEXIST and os.path.isdir(dest):
pass
else:
raise
else:
try:
member_f = archive.open(member)
except TypeError:
member_f = tarfile.ExFileObject(archive, member)
with open(dest, "wb") as f:
f.write(member_f.read())
member_f.close()
archive.close()
result["changed"] = True
return result
+70
View File
@@ -0,0 +1,70 @@
---
# The following variables will be set by the runner of this playbook:
# src: /tmp/some/path/private_data_dir/
- name: Poll for status of active job.
hosts: all
gather_facts: false
collections:
- ansible.posix
tasks:
- name: "Output job the playbook is running for"
debug:
msg: "Checking on job {{ job_id }}"
- name: Determine if daemon process is alive.
shell: "ansible-runner is-alive {{src}}"
register: is_alive
ignore_errors: true
- name: Copy artifacts from the isolated host.
synchronize:
src: "{{src}}/artifacts/"
dest: "{{src}}/artifacts/"
mode: pull
delete: true
recursive: true
when: ansible_kubectl_config is not defined
- name: Copy daemon log from the isolated host
synchronize:
src: "{{src}}/daemon.log"
dest: "{{src}}/daemon.log"
mode: pull
when: ansible_kubectl_config is not defined
- name: Copy artifacts from pod
synchronize:
src: "{{src}}/artifacts/"
dest: "{{src}}/artifacts/"
mode: pull
delete: true
recursive: true
set_remote_user: false
rsync_opts:
- "--blocking-io"
- "--rsh=$RSH"
environment:
RSH: "oc rsh --config={{ ansible_kubectl_config }}"
delegate_to: localhost
when: ansible_kubectl_config is defined
- name: Copy daemon log from pod
synchronize:
src: "{{src}}/daemon.log"
dest: "{{src}}/daemon.log"
mode: pull
set_remote_user: false
rsync_opts:
- "--blocking-io"
- "--rsh=$RSH"
environment:
RSH: "oc rsh --config={{ ansible_kubectl_config }}"
delegate_to: localhost
when: ansible_kubectl_config is defined
- name: Fail if previous check determined that process is not alive.
fail:
msg: "isolated task is still running"
when: "is_alive.rc == 0"
+31
View File
@@ -0,0 +1,31 @@
---
# The following variables will be set by the runner of this playbook:
# cleanup_dirs: ['/tmp/path/private_data_dir/', '/tmp//path/proot_temp_dir/']
# private_data_dir: '/tmp/path/private_data_dir/'
- name: Clean up from isolated job run.
hosts: all
gather_facts: false
tasks:
- name: cancel the job
command: "ansible-runner stop {{private_data_dir}}"
ignore_errors: true
- name: remove build artifacts
file:
path: '{{item}}'
state: absent
register: result
with_items: "{{cleanup_dirs}}"
until: result is succeeded
ignore_errors: true
retries: 3
delay: 5
- name: fail if build artifacts were not cleaned
fail:
msg: 'Unable to cleanup build artifacts'
when: not result is succeeded
+12
View File
@@ -0,0 +1,12 @@
---
- name: Periodic background status check of isolated instances.
hosts: all
gather_facts: false
tasks:
- name: Get capacity of the instance
awx_capacity:
- name: Remove any stale temporary files
awx_isolated_cleanup:
+44
View File
@@ -0,0 +1,44 @@
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'tower'}
DOCUMENTATION = '''
---
module: insights
short_description: gather all maintenance plan playbooks for an insights account
description:
- Supply insights Credentials to download all playbooks for all maintenance plans.
The totality of the plans are versioned based on the http ETag response.
version_added: "2.3"
options:
insights_url:
description:
- The base url of the insights api. Most likely https://insights.redhat.com
required: true
username:
description:
- Insights basic auth username.
required: true
password:
description:
- Insights basic auth password.
required: true
project_path:
description:
- Directory to write all playbooks and the special .version to.
required: true
notes:
- Returns version
author:
- "Chris Meyers"
'''
EXAMPLES = '''
- insights:
insights_url: "https://insights.redhat.com"
username: "cmoney"
password: "get_paid"
project_path: "/var/lib/awx/projects/_5_insights"
'''
+40
View File
@@ -0,0 +1,40 @@
ANSIBLE_METADATA = {
"metadata_version": "1.0",
"status": ["stableinterface"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: project_archive
short_description: unpack a project archive
description:
- Unpacks an archive that contains a project, in order to support handling versioned
artifacts from (for example) GitHub Releases or Artifactory builds.
- Handles projects in the archive root, or in a single base directory of the archive.
version_added: "2.9"
options:
src:
description:
- The source archive of the project artifact
required: true
project_path:
description:
- Directory to write the project archive contents
required: true
force:
description:
- Files in the project_path will be overwritten by matching files in the archive
default: False
author:
- "Philip Douglass" @philipsd6
"""
EXAMPLES = """
- project_archive:
src: "{{ project_path }}/.archive/project.tar.gz"
project_path: "{{ project_path }}"
force: "{{ scm_clean }}"
"""
+214
View File
@@ -0,0 +1,214 @@
---
# The following variables will be set by the runner of this playbook:
# projects_root: Global location for caching project checkouts and roles and collections
# should not have trailing slash on end
# local_path: Path within projects_root to use for this project
# project_path: A simple join of projects_root/local_path folders
# scm_url: https://server/repo
# insights_url: Insights service URL (from configuration)
# scm_branch: branch/tag/revision (HEAD if unset)
# scm_clean: true/false
# scm_username: username (only for svn/insights)
# scm_password: password (only for svn/insights)
# scm_accept_hostkey: true/false (only for git, set automatically)
# scm_refspec: a refspec to fetch in addition to obtaining version
# roles_enabled: Value of the global setting to enable roles downloading
# collections_enabled: Value of the global setting to enable collections downloading
# awx_version: Current running version of the awx or tower as a string
# awx_license_type: "open" for AWX; else presume Tower
- hosts: localhost
gather_facts: false
connection: local
name: Update source tree if necessary
tasks:
- name: delete project directory before update
file:
path: "{{project_path|quote}}"
state: absent
tags:
- delete
- block:
- name: update project using git
git:
dest: "{{project_path|quote}}"
repo: "{{scm_url}}"
version: "{{scm_branch|quote}}"
refspec: "{{scm_refspec|default(omit)}}"
force: "{{scm_clean}}"
accept_hostkey: "{{scm_accept_hostkey|default(omit)}}"
register: git_result
- name: Set the git repository version
set_fact:
scm_version: "{{ git_result['after'] }}"
when: "'after' in git_result"
tags:
- update_git
- block:
- name: update project using svn
subversion:
dest: "{{project_path|quote}}"
repo: "{{scm_url|quote}}"
revision: "{{scm_branch|quote}}"
force: "{{scm_clean}}"
username: "{{scm_username|default(omit)}}"
password: "{{scm_password|default(omit)}}"
environment:
LC_ALL: 'en_US.UTF-8'
register: svn_result
- name: Set the svn repository version
set_fact:
scm_version: "{{ svn_result['after'] }}"
when: "'after' in svn_result"
- name: parse subversion version string properly
set_fact:
scm_version: "{{scm_version|regex_replace('^.*Revision: ([0-9]+).*$', '\\1')}}"
tags:
- update_svn
- block:
- name: Ensure the project directory is present
file:
dest: "{{project_path|quote}}"
state: directory
- name: Fetch Insights Playbook(s)
insights:
insights_url: "{{insights_url}}"
username: "{{scm_username}}"
password: "{{scm_password}}"
project_path: "{{project_path}}"
awx_license_type: "{{awx_license_type}}"
awx_version: "{{awx_version}}"
register: results
- name: Save Insights Version
set_fact:
scm_version: "{{results.version}}"
when: results is defined
tags:
- update_insights
- block:
- name: Ensure the project archive directory is present
file:
dest: "{{ project_path|quote }}/.archive"
state: directory
- name: Get archive from url
get_url:
url: "{{ scm_url|quote }}"
dest: "{{ project_path|quote }}/.archive/"
url_username: "{{ scm_username|default(omit) }}"
url_password: "{{ scm_password|default(omit) }}"
force_basic_auth: true
register: get_archive
- name: Unpack archive
project_archive:
src: "{{ get_archive.dest }}"
project_path: "{{ project_path|quote }}"
force: "{{ scm_clean }}"
when: get_archive.changed or scm_clean
register: unarchived
- name: Find previous archives
find:
paths: "{{ project_path|quote }}/.archive/"
excludes:
- "{{ get_archive.dest|basename }}"
when: unarchived.changed
register: previous_archive
- name: Remove previous archives
file:
path: "{{ item.path }}"
state: absent
loop: "{{ previous_archive.files }}"
when: previous_archive.files|default([])
- name: Set scm_version to archive sha1 checksum
set_fact:
scm_version: "{{ get_archive.checksum_src }}"
tags:
- update_archive
- name: Repository Version
debug:
msg: "Repository Version {{ scm_version }}"
tags:
- update_git
- update_svn
- update_insights
- update_archive
- hosts: localhost
gather_facts: false
connection: local
name: Install content with ansible-galaxy command if necessary
vars:
yaml_exts:
- {ext: .yml}
- {ext: .yaml}
tasks:
- block:
- name: detect roles/requirements.(yml/yaml)
stat:
path: "{{project_path|quote}}/roles/requirements{{ item.ext }}"
with_items: "{{ yaml_exts }}"
register: doesRequirementsExist
- name: fetch galaxy roles from requirements.(yml/yaml)
command: >
ansible-galaxy role install -r {{ item.stat.path }}
--roles-path {{projects_root}}/.__awx_cache/{{local_path}}/stage/requirements_roles
{{ ' -' + 'v' * ansible_verbosity if ansible_verbosity else '' }}
args:
chdir: "{{project_path|quote}}"
register: galaxy_result
with_items: "{{ doesRequirementsExist.results }}"
when: item.stat.exists
changed_when: "'was installed successfully' in galaxy_result.stdout"
environment:
ANSIBLE_FORCE_COLOR: false
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
when: roles_enabled|bool
tags:
- install_roles
- block:
- name: detect collections/requirements.(yml/yaml)
stat:
path: "{{project_path|quote}}/collections/requirements{{ item.ext }}"
with_items: "{{ yaml_exts }}"
register: doesCollectionRequirementsExist
- name: fetch galaxy collections from collections/requirements.(yml/yaml)
command: >
ansible-galaxy collection install -r {{ item.stat.path }}
--collections-path {{projects_root}}/.__awx_cache/{{local_path}}/stage/requirements_collections
{{ ' -' + 'v' * ansible_verbosity if ansible_verbosity else '' }}
args:
chdir: "{{project_path|quote}}"
register: galaxy_collection_result
with_items: "{{ doesCollectionRequirementsExist.results }}"
when: item.stat.exists
changed_when: "'Installing ' in galaxy_collection_result.stdout"
environment:
ANSIBLE_FORCE_COLOR: false
ANSIBLE_COLLECTIONS_PATHS: "{{projects_root}}/.__awx_cache/{{local_path}}/stage/requirements_collections"
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
when:
- "ansible_version.full is version_compare('2.9', '>=')"
- collections_enabled|bool
tags:
- install_collections
+61
View File
@@ -0,0 +1,61 @@
---
# The following variables will be set by the runner of this playbook:
# src: /tmp/some/path/private_data_dir
# dest: /tmp/some/path/
- name: Prepare data, dispatch job in isolated environment.
hosts: all
gather_facts: false
vars:
secret: "{{ lookup('pipe', 'cat ' + src + '/env/ssh_key') }}"
collections:
- ansible.posix
tasks:
- name: "Output job the playbook is running for"
debug:
msg: "Checking on job {{ job_id }}"
- name: synchronize job environment with isolated host
synchronize:
copy_links: true
src: "{{ src }}"
dest: "{{ dest }}"
when: ansible_kubectl_config is not defined
- name: synchronize job environment with remote job container
synchronize:
copy_links: true
src: "{{ src }}"
dest: "{{ dest }}"
set_remote_user: false
rsync_opts:
- "--blocking-io"
- "--rsh=$RSH"
environment:
RSH: "oc rsh --config={{ ansible_kubectl_config }}"
delegate_to: localhost
when: ansible_kubectl_config is defined
- local_action: stat path="{{src}}/env/ssh_key"
register: key
- name: create a named pipe for secret environment data
command: "mkfifo {{src}}/env/ssh_key"
when: key.stat.exists
- name: spawn the playbook
command: "ansible-runner start {{src}} -p '{{playbook}}' -i {{ident}}"
when: playbook is defined
- name: spawn the adhoc command
command: "ansible-runner start {{src}} -m {{module}} -a {{module_args}} -i {{ident}}"
when: module is defined
- name: write the secret environment data
mkfifo:
content: "{{secret}}"
path: "{{src}}/env/ssh_key"
when: key.stat.exists
no_log: true