Skip to content

Commit

Permalink
Merge pull request #169 from CloudBytes-Academy/article
Browse files Browse the repository at this point in the history
Article
  • Loading branch information
rehanhaider authored Oct 29, 2023
2 parents 20f0550 + eace281 commit 6768d4c
Show file tree
Hide file tree
Showing 5 changed files with 254 additions and 11 deletions.
29 changes: 18 additions & 11 deletions content/aws/12500000-aws-cli-intro.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
Title: How to install and configure AWS CLI on Linux with Autocompletion
Date: 2022-06-12
Date: 2023-10-28
Category: AWS Academy
Series: AWS CLI
Series_index: 1
Tags: aws, linux
Author: Rehan Haider
Summary: A guide to how to install and configure AWS CLI on Ubuntu Linux with Autocompletion turned on
Expand Down Expand Up @@ -101,9 +103,9 @@ AWS CLI relies on a module named `aws_completer` for autocompletion. This module
1. `aws_completer` to be on the `PATH`
2. Enable command completion in the shell

### Add aws_completer to the PATH
### Ensure `aws_completer` is added to the PATH

**Step 1**: First, check if the `aws_completer` is already on path by running the following command:
First, check if the `aws_completer` is already on path by running the following command:

```bash
which aws_completer
Expand All @@ -112,9 +114,14 @@ which aws_completer
This should result in the following output:
![Which AWS Completer]({static}/images/aws-academy/12500000-which-aws-completer.png)

If you don't see any output, it means that the `aws_completer` is not on the `PATH`.

**Step 2**: Find `aws_completer` executable file by running the following command:
If you get the above output, it means that the `aws_completer` is already on the `PATH`. So you can skip to [Enable command completion in the shell](#enable-command-completion-in-the-shell) section.

Otherwise if you don't see any output, it means that the `aws_completer` is not on the `PATH`, follow the steps below to add it to the `PATH`.

### Add `aws_completer` to the PATH

**Step 1**: Find `aws_completer` executable file by running the following command:

```bash
find / -name aws_completer
Expand All @@ -124,15 +131,15 @@ This will search for the `aws_completer` executable file in your filesystem. E.g

![Find AWS Completer]({static}/images/aws-academy/12500000-aws-completer-path.png)

**Step 3**: Identify your shell and add the `aws_completer` to the `PATH`.
**Step 2**: Identify your shell and add the `aws_completer` to the `PATH`.

Run `echo $SHELL` to see what shell you are using.

![Echo Shell]({static}/images/aws-academy/12500000-shell-type.png)

If you are using some other shell, you will get a different output.

**Step 4**: Find the shell configuration file for your shell.
**Step 3**: Find the shell configuration file for your shell.

Depending on the shell you're using, your shell's profile file will be one of the following:

Expand All @@ -152,7 +159,7 @@ E.g. in my case, I am using `bash` and my profile file is `.profile` thus runnin

![Find Shell Profile]({static}/images/aws-academy/12500000-bash-profile.png)

**Step 5**: Add the `aws_completer` to the `PATH`
**Step 4**: Add the `aws_completer` to the `PATH`

Now open the shell profile using any text editor, e.g. `vi` or `nano` and add the following line to the end of the file and replace `<path to aws_completer directory>` with the path to the `aws_completer` executable file discovered in step 2:

Expand All @@ -161,7 +168,7 @@ Now open the shell profile using any text editor, e.g. `vi` or `nano` and add th
export PATH=<path to aws_completer directory>:$PATH
```

**Step 6**: Restart your shell
**Step 5**: Restart your shell

Depending upon the shell, restart your shell by running the following command by replacing `<your profile file>` with the name of your shell profile file as per step 4:

Expand Down Expand Up @@ -204,10 +211,10 @@ complete aws 'p/*/`aws_completer`/'

### Verify that the command completion is working

Reload your shell again as per step 6.
Reload your shell configuration file, replace `<your profile file>` with the appropriate shell configure file

```text
source ~/<your profile file>
source ~/<your shell config file>
```

Then type `aws s3` and press `TAB` to see the list of available commands.
Expand Down
49 changes: 49 additions & 0 deletions content/aws/12501000-cli-get-account-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
Title: Get your AWS Account ID using AWS CLI
Date: 2023-12-28
Category: AWS Academy
Series: AWS CLI
Series_index: 2
Tags: aws, linux
Author: Rehan Haider
Summary: A guide to how to get your AWS Account ID using AWS CLI
Keywords: AWS, cli



If you have not already done so, [install and configure AWS CLI]({filename}12500000-aws-cli-intro.md).

## Get your AWS Account ID

To get your AWS Account ID, run the following command:

```bash
aws sts get-caller-identity --query Account --output text
```

This command uses the Security Token Service (STS) get-caller-identity function, which returns details about the IAM user or role making the call. The --query Account fetches only the Account ID, and --output text ensures the result is displayed as plain text.

![STS caller identify]({static}/images/aws-academy/12501000-01-cli-id-output-text.png)


### Understanding the output

The output of the `get-caller-identity` command provides three pieces of information:

* `UserId`: The unique identifier for the entity making the call. For an IAM user, this is the user's unique ID.
* `Account`: Your AWS Account ID.
* `Arn`: The Amazon Resource Name (ARN) of the IAM user or role making the call.

By using the `--query Account` parameter, we specifically extract the Account value.


### Saving the output to file

You can save the output of the `get-caller-identity` command to a file using the `>` operator as shown below:

```bash
aws sts get-caller-identity --query Account --output text > account-id.txt
```

This will save the output to a file called `account-id.txt` in the current directory.

![STS caller identify]({static}/images/aws-academy/12501000-02-cli-id-to-file.png)
187 changes: 187 additions & 0 deletions content/aws/60001000-cdk-how-to-get-arn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
Title: How to get the ARN of a resource using AWS CDK
Date: 2023-10-29
Category: AWS Academy
Tags: aws, cdk, python
Author: Rehan Haider
Summary: A guide on how to get the ARN of a resource using AWS CDK
Keywords: ARN, AWS, CDK


ARN (Amazon Resource Name) is a unique identifier automatically assigned to every AWS resource when it is created. The ARN is used to uniquely identify the resource across all of AWS including accounts, regions, and services.

# ARN Format

As explained in the [AWS documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html), an ARN has the following format depending on the resource type:

```
arn:partition:service:region:account-id:resource-id
arn:partition:service:region:account-id:resource-type/resource-id
arn:partition:service:region:account-id:resource-type:resource-id
```

In the above format, the following placeholders are used:

1. `partition` - The partition that the resource is in. For standard AWS regions, the partition is `aws`. If you have resources in other partitions, the partition is `aws-cn` for China and `aws-us-gov` for AWS GovCloud (US).
2. `service` - The service namespace that identifies the AWS product (for example, `s3`, `iam`, `codecommit`, `ec2`, etc.).
3. `region` - The AWS Region that the resource resides in. For example, `us-east-1`.
4. `account-id`: The ID of the AWS account that owns the resource, without the hyphens. For example, `123456789012`.
5. `resource-type` - The resource type (for example, `instance`, `bucket`, `user`, etc.).
6. `resource-id`: The resource ID. This depends on the service namespace. For example, an Amazon S3 bucket is named using the path style `bucket_name`, and so is identified by `bucket_name`.


## How to get the ARN of a resource using AWS CDK

There are a few ways to get the ARN of a resource using AWS CDK. Some of them are:

1. [Using `<resource>_arn` property](#using-resource_arn-property)
2. [Using `attr_arn` method from CFN resource](#using-attr_arn-method-fromm-cfn-resource)
3. Using GetAtt method from Fn class

### Using `<resource>_arn` property

To get the ARN of a resource using AWS CDK, you can use the `<resource>_arn` property. For example, to get the ARN of an S3 bucket, you can use the `bucket_arn` property as shown below:

```python
# filename: cdk_app/s3_stack.py
from aws_cdk import (
Stack,
aws_s3 as s3,
RemovalPolicy,
)

from aws_cdk import CfnOutput # πŸ‘ˆπŸ½ Import the CfnOutput class
from constructs import Construct


class S3Stack(Stack):
BUCKET_ID = "MyS3Bucket"

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

myBucket = s3.Bucket(self, self.BUCKET_ID, removal_policy=RemovalPolicy.DESTROY)
bucket_arn = myBucket.bucket_arn # πŸ‘ˆπŸ½ Get the ARN of the bucket

# πŸ‘‡πŸ½ Print the bucket ARN to console
print(f"Bucker ARN: {bucket_arn}")

# πŸ‘‡πŸ½ Output the bucket ARN to use in other stacks
CfnOutput(self, "S3BucketARN", value=myBucket.bucket_arn, export_name="MyS3BucketARN")
```

Similarly, to get the ARN of a DynamoDB table, you can use the `table_arn` property as shown below:

```python
# filename: cdk_app/dynamodb_stack.py
from aws_cdk import (
Stack,
aws_dynamodb as ddb,
RemovalPolicy,
)

from constructs import Construct


class DynamoDBStack(Stack):
TABLE_ID = "MyDynamoDBTable"

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

myTable = ddb.Table(
self,
self.TABLE_ID,
partition_key={"name": "id", "type": ddb.AttributeType.STRING},
removal_policy=RemovalPolicy.DESTROY,
)

# πŸ‘‡πŸ½ Print the table ARN to console
print(f"Table ARN: {myTable.table_arn}")
```

### Using `attr_arn` method fromm CFN resource

You can also use the `attr_arn` method from the [L1 CFN]({filename}50003000-cdk-constructs.md) resource to get the ARN of a resource. For example, let's modify our `s3_stack.py` to use the `attr_arn` method as shown below:


```python
# filename: cdk_app/s3_stack.py

from aws_cdk import (
Stack,
aws_s3 as s3,
RemovalPolicy,
)

from aws_cdk import CfnOutput # πŸ‘ˆπŸ½ Import the CfnOutput class
from constructs import Construct


class S3Stack(Stack):
BUCKET_ID = "MyS3Bucket"

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

myBucket = s3.Bucket(self, self.BUCKET_ID, removal_policy=RemovalPolicy.DESTROY)

# πŸ‘‡πŸ½ Get the CFN Bucket resource.
cfn_bucket: s3.CfnBucket = myBucket.node.default_child

bucket_arn = cfn_bucket.attr_arn # πŸ‘ˆπŸ½ Get the ARN of the bucket

# πŸ‘‡πŸ½ Output the bucket ARN
CfnOutput(self, "S3BucketARN", value=bucket_arn, export_name="MyS3BucketARN")
```

In the above code, we are using the `node.default_child` property to get the CFN resource for the S3 bucket. Then we are using the `attr_arn` method to get the ARN of the bucket.

!!! note
Notice we hinted the type of the `cfn_bucket` variable as `s3.CfnBucket`. This is because the `node.default_child` property returns a generic `CfnResource` type. We need to hint the type to `s3.CfnBucket` to get access to the `attr_arn` method.

## Using GetAtt method from Fn class

You can also use the `Fn.get_att` method to get the ARN of a resource. For example, let's modify our `s3_stack.py` to use the `Fn.get_att` method as shown below:

```python
# filename: cdk_app/s3_stack.py

from aws_cdk import (
Stack,
aws_s3 as s3,
RemovalPolicy,
Fn, # πŸ‘ˆπŸ½ Import the Fn class
)

from aws_cdk import CfnOutput # πŸ‘ˆπŸ½ Import the CfnOutput class
from constructs import Construct


class S3Stack(Stack):
BUCKET_ID = "MyS3Bucket"

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

myBucket = s3.Bucket(self, self.BUCKET_ID, removal_policy=RemovalPolicy.DESTROY)

# πŸ‘‡πŸ½ Get the CFN Bucket resource
cfn_bucket: s3.CfnBucket = myBucket.node.default_child

bucket_arn = Fn.get_att(cfn_bucket.logical_id, "Arn").to_string()

# πŸ‘‡πŸ½ Output the bucket ARN
CfnOutput(self, "S3BucketARN", value=bucket_arn, export_name="MyS3BucketARN")
```

To use the `Fn.get_att` method, you need to pass the logical ID of the resource and the attribute name as arguments. We also need to convert the output of the `Fn.get_att` method to a string using the `to_string` method.


## Conclusion

The above methods are common ways of getting the ARN of a resource using AWS CDK. Using the `<resource>_arn` property is the easiest way to get the ARN of a resource. However, if you need to get the ARN of a resource that doesn't have a L2 construct yet and is not supported by AWS CDK, you can use the `attr_arn` method from the CFN resource or the `Fn.get_att` method from the Fn class.

```python
myBucket = s3.Bucket(self, self.BUCKET_ID, removal_policy=RemovalPolicy.DESTROY)
bucket_arn = myBucket.bucket_arn # πŸ‘ˆπŸ½ Get the ARN of the bucket
```
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 6768d4c

Please sign in to comment.