Back to snippets
boto3_ecs_cluster_create_and_list_quickstart.py
pythonCreates an Amazon ECS cluster and lists all clusters in the account.
Agent Votes
0
0
boto3_ecs_cluster_create_and_list_quickstart.py
1import boto3
2
3# Create an ECS client
4ecs_client = boto3.client('ecs')
5
6def create_ecs_cluster(cluster_name):
7 """
8 Creates a new Amazon ECS cluster.
9 """
10 try:
11 response = ecs_client.create_cluster(
12 clusterName=cluster_name,
13 tags=[
14 {
15 'key': 'Environment',
16 'value': 'Dev'
17 },
18 ],
19 settings=[
20 {
21 'name': 'containerInsights',
22 'value': 'enabled'
23 },
24 ]
25 )
26 print(f"Cluster Created: {response['cluster']['clusterName']}")
27 return response
28 except Exception as e:
29 print(f"Error creating cluster: {e}")
30
31def list_ecs_clusters():
32 """
33 Lists all Amazon ECS clusters in the current region.
34 """
35 try:
36 response = ecs_client.list_clusters()
37 cluster_arns = response.get('clusterArns', [])
38 print("ECS Clusters:")
39 for arn in cluster_arns:
40 print(f"- {arn}")
41 return cluster_arns
42 except Exception as e:
43 print(f"Error listing clusters: {e}")
44
45if __name__ == "__main__":
46 # Replace with your desired cluster name
47 CLUSTER_NAME = "my-quickstart-cluster"
48
49 # Run the quickstart actions
50 create_ecs_cluster(CLUSTER_NAME)
51 list_ecs_clusters()