-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathtasks.py
More file actions
225 lines (190 loc) · 6.13 KB
/
tasks.py
File metadata and controls
225 lines (190 loc) · 6.13 KB
1
2
3
4
5
6
7
8
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import os
import subprocess
import sys
import warnings
from pathlib import Path
import boto3
import dotenv
from invoke import task
from cdk.lambdas.ssm_run_command_once.command_runner import (
RunOncePerTagRunCommandClient,
)
def get_ssm_parameter_value(client, key):
response = client.get_parameter(Name=key)
return response["Parameter"]["Value"]
def get_rds_connection_string(
profile,
user="postgres",
db_name=None,
host=None,
password=None,
):
session = boto3.session.Session(profile_name=profile)
ssm_client = session.client("ssm")
if (db_name := db_name) is None:
db_name = get_ssm_parameter_value(ssm_client, "RDS_DB_NAME")
if (host := host) is None:
host = get_ssm_parameter_value(ssm_client, "RDS_DB_HOST")
if (password := password) is None:
password = get_ssm_parameter_value(ssm_client, "RDS_DB_PASSWORD")
return f"postgresql://{user}:{password}@{host}/{db_name}"
def git_revision():
try:
out = subprocess.check_output(["git", "rev-parse", "HEAD"])
revision = out.strip().decode("ascii")
except OSError:
revision = "Unknown"
return revision
def bootstrap_django():
with warnings.catch_warnings():
warnings.simplefilter("ignore")
dotenv.read_dotenv()
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "polling_stations.settings")
import django
django.setup()
sys.path.append(str(Path.cwd() / "polling_stations/apps/"))
@task
def import_council(ctx, environment, reg_code):
"""
AWS_PROFILE=dev-wdiv-dc inv import-council development MDE
"""
bootstrap_django()
from councils.models import Council
council = Council.objects.get(council_id=reg_code)
import_command = council.import_script_path.split("/")[-1][:-3]
tag_name = "dc-environment"
tag_value = environment
command = (
f"runuser -l polling_stations -c '/usr/bin/manage-py-command {import_command}'"
)
runner = RunOncePerTagRunCommandClient(tag_name=tag_name, tag_value=tag_value)
runner.run_command_on_single_instance(command)
print(f"Running {import_command} on {environment}")
print(runner.command_invocation)
runner.poll_response()
@task
def teardown_council(ctx, environment, reg_code):
"""
AWS_PROFILE=dev-wdiv-dc inv teardown-council development BRO
"""
tag_name = "dc-environment"
tag_value = environment
command = f"runuser -l polling_stations -c '/usr/bin/manage-py-command teardown --council {reg_code}'"
runner = RunOncePerTagRunCommandClient(tag_name=tag_name, tag_value=tag_value)
runner.run_command_on_single_instance(command)
print(runner.command_invocation)
runner.poll_response()
@task
def describe_parameters(ctx, profile=os.environ.get("AWS_PROFILE", None)):
session = boto3.session.Session(profile_name=profile)
ssm_client = session.client("ssm")
for parameter in ssm_client.describe_parameters()["Parameters"]:
print(
f"{parameter['Name']} => {get_ssm_parameter_value(ssm_client,parameter['Name'])}"
)
print(f"{parameter.get('Description')}")
print()
@task(
help={
"profile": "Required. Name of AWS profile to be called with",
}
)
def rds_psql(
ctx,
profile,
user="postgres",
db_name=None,
host=None,
password=None,
print=False,
):
"""
Start psql client to rds associate with <profile> account.
NB This does not mean the rds is in that account.
Merely the DB that parameter store points at. i.e. 'stage' might point at a db in 'dev'
"""
conn_string = get_rds_connection_string(
profile, user=user, db_name=db_name, host=host, password=password
)
if print:
sys.stdout.write(f"\npsql {conn_string}\n\n")
return
ctx.run(f"psql {conn_string}")
@task(
help={
"profile": "Required. Name of AWS profile to be called with",
}
)
def list_rds_dbs(
ctx,
profile,
user="postgres",
db_name=None,
host=None,
password=None,
):
conn_string = get_rds_connection_string(
profile, user=user, db_name=db_name, host=host, password=password
)
ctx.run(f'psql {conn_string} -c "\\l"')
@task(
help={
"profile": "Required. Name of AWS profile to be called with",
}
)
def list_subscriptions(
ctx,
profile,
user="postgres",
db_name=None,
host=None,
password=None,
fmt="csv",
):
conn_string = get_rds_connection_string(
profile, user=user, db_name=db_name, host=host, password=password
)
ctx.run(f'psql {conn_string} -c "select * from pg_replication_slots;" --{fmt}')
@task
def list_db_parameters(ctx, profile, name):
"""
List parameters in parameter group "Name"
Examples:
inv list-db-parameters --profile prod-wdiv-dc | jq '.[][] | select(.Source | test("user")) | {ParameterName, ParameterValue, ApplyMethod}'
"""
ctx.run(
f"""
aws --profile {profile} rds describe-db-parameters \
--db-parameter-group-name {name}"""
)
@task(
help={
"profile": "Required. Name of AWS profile to be called with",
"output": "Output Format. Defaults to 'table'. Valid choices: table|json|text|yaml|yaml-stream",
}
)
def describe_instances(ctx, profile, output="table"):
"""
Describe EC2 Instances in <profile> aws environment
Examples:
inv describe-instances --profile prod-wdiv-dc
inv describe-instances --profile prod-wdiv-dc --output json | jq '.[][]' | mlr --ijson --oxtab cat
"""
query = "Reservations[*].Instances[*].{PublicIP:PublicIpAddress,Type:InstanceType,Name:Tags[?Key=='Name']|[0].Value,InstanceID:InstanceId,Status:State.Name}"
command = f"""
aws ec2 describe-instances \
--profile {profile} \
--filters "Name=instance-state-name,Values=running" \
--query "{query}" \
--output {output}
"""
ctx.run(command)
def create_deployment(ctx, profile, commit=None):
"""
Create a CodeDeploy deployment
"""
if not commit:
commit = git_revision()
ctx.run(
f"AWS_PROFILE={profile} COMMIT_SHA={commit} python deploy/create_deployment.py"
)