Showing posts with label aws. Show all posts
Showing posts with label aws. Show all posts

Friday, February 7, 2025

Search by action all AWS IAM Policies in your account

Find all policies that contain a specific action(grep by string)

AWS Iam manage access to AWS cloud trough different entities that narrow down to policies that have actions.

One such situation be the following, you want to find all policies that contain the action ec2:CreateVolume under your AWS account.

To find all policies that contain ec2:CreateVolume using the Web Ui can be time consuming and error prone when you need to search multiple policies, especially if you have inline and managed (AWS or customer).

So cli to the rescue !

Examples

To search trough use aws iam and get-account-authorization-details.

All policies

To note this output will not include inline policies.

In the case of ec2:CreateVolume this should do

aws iam \
    get-account-authorization-details \
    --query 'Policies[?contains(PolicyVersionList[].Document[].Statement[].Action[], `ec2:CreateVolume`)].{Arn:Arn, Path:Path}'

If any policy contains the action ec2:CreateVolume will show something like


[
    {
        "Arn": "arn:aws:iam::000000000000:policy/path/subPath/NameOfPolicy",
        "Path": "/path/subPath/"
    },
    {
        "Arn": "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy",
        "Path": "/"
    },
    {
        "Arn": "arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy",
        "Path": "/service-role/"
    }
]

So the first entry is a customer managed policy, the account id is zeroed in this example but will show the actual account id, the path and subPath are namespaces as where the policy was written.

The second and third don’t have an account id and the name starts with Amazon, these are managed by AWS.

All groups with inline policies

aws iam \
    get-account-authorization-details \
    --query 'GroupDetailList[?GroupPolicyList[].PolicyDocument[].Statement[].Action!=null && contains(GroupPolicyList[].PolicyDocument[].Statement[].Action[], `ec2:CreateVolume`)].{GroupArn:Arn, PolicyName:GroupPolicyList[].PolicyName}'

All users with inline policies

aws iam \
    get-account-authorization-details \
    --query 'UserDetailList[?UserPolicyList[].PolicyDocument[].Statement[].Action!=null && contains(UserPolicyList[].PolicyDocument[].Statement[].Action[], `ec2:CreateVolume`)].{UserArn:Arn, PolicyName:UserPolicyList[].PolicyName}[]' 

All roles with inline policies

aws iam \
    get-account-authorization-details \
    --query 'RoleDetailList[?RolePolicyList[].PolicyDocument[].Statement[].Action!=null && contains(RolePolicyList[].PolicyDocument[].Statement[].Action[], `ec2:CreateVolume`)].{RoleArn:Arn, PolicyName:RolePolicyList[].PolicyName}'

Friday, April 12, 2024

Databricks AWS private link with conditional DNS forwarder

Databricks allows workspace to be accessible via a private ip so not publicly available.
This is useful in some cases where you want to restrict users to used it only if are connected to a VPN or equivalent.
These are the steps to achive this goal
  1. Create a custom VPC in AWS
  2. Connect the VPC to your infrastructure (VPN/Direct Connect)
  3. Create VPC Endpoint for frontend and backend
  4. Register private link in the databricks account and associate it to your workspace
  5. Change access mode to Private from Public in the Private Access Settings
  6. Create a private zone in Route53
  7. Create an inbound resolver in Route53
  8. Add an A entry in the zone that points to the address of the VPC Endpoint (step3)
  9. Add a forwarder in your Private DNS to point to the inbound resolver (step 7) ip address(es)
For more details Databricks documentation explains in more details docs.databricks.com (search for private link). Once all is in place the flow is
+---------+                               +-------------+                                            +-----------+ +-------------------------+                                         +-------------+
| Client  |                               | PrivateDns  |                                            | PublicDns | | Route53InboundResolver  |                                         | Route53Zone |
+---------+                               +-------------+                                            +-----------+ +-------------------------+                                         +-------------+
     |                                           |                                                         |                    |                                                             |
     | my-workspace.cloud.databricks.com         |                                                         |                    |                                                             |
     |------------------------------------------>|                                                         |                    |                                                             |
     |                                           |                                                         |                    |                                                             |
     |                                           | my-workspace.cloud.databricks.com                       |                    |                                                             |
     |                                           |-------------------------------------------------------->|                    |                                                             |
     |                                           |                                                         |                    |                                                             |
     |                                           |       CNAME nvirginia.privatelink.cloud.databricks.com. |                    |                                                             |
     |                                           |<--------------------------------------------------------|                    |                                                             |
     |                                           |                                                         |                    |                                                             |
     |                                           | nvirginia.privatelink.cloud.databricks.com ?            |                    |                                                             |
     |                                           |----------------------------------------------------------------------------->|                                                             |
     |                                           |                                                         |                    |                                                             |
     |                                           |                                                         |                    | nvirginia.privatelink.cloud.databricks.com ?                |
     |                                           |                                                         |                    |------------------------------------------------------------>|
     |                                           |                                                         |                    |                                                             |
     |                                           |                                                         |                    |                                      Address is 172.16.0.10 |
     |                                           |                                                         |                    |<------------------------------------------------------------|
     |                                           |                                                         |                    |-----------------------------------------------------------\ |
     |                                           |                                                         |                    || nvirginia.privatelink.cloud.databricks.com A 172.16.0.10 |-|
     |                                           |                                                         |                    ||----------------------------------------------------------| |
     |                                           |                                                         |                    |                                                             |
     |                                           |                                                Answer address is 172.16.0.10 |                                                             |
     |                                           |<-----------------------------------------------------------------------------|                                                             |
     |                                           |                                                         |                    |                                                             |
     |                    Connect to 172.16.0.10 |                                                         |                    |                                                             |
     |<------------------------------------------|                                                         |                    |                                                             |
     |                                           |                                                         |                    |                                                             |



Wednesday, December 29, 2021

Victoria metrics on Aws EC2 instance

Will configure one single EC2 instance as a Victoria Metrics server to be used as Promethues storage.

The access to VM(victoria metrics) is done via port 8247 and is protected by http basic auth. All traffic is encrypted with a self sign certificate.

Installation

Will install manually by downloading the releases from github and configure the local system.

Download binaries

# create a group and user for vm
$ sudo groupadd -r victoriametrics
$ sudo useradd -g victoriametrics victoriametrics
 
# download
$ curl -L https://github.com/VictoriaMetrics/VictoriaMetrics/releases/download/v1.70.0/victoria-metrics-amd64-v1.70.0.tar.gz --output victoria-metrics-amd64-v1.70.0.tar.gz

# unpack and install it
$ sudo tar xvf victoria-metrics-amd64-v1.70.0.tar.gz -C /usr/local/bin/
$ chown root:root /usr/local/bin/victoria-metrics-prod

# create data directory
$ sudo mkdir /var/lib/victoria-metrics-data
$ chown -v victoriametrics:victoriametrics /var/lib/victoria-metrics-data

Configure the service

cat >> /etc/systemd/system/victoriametrics.service <<EOF
[Unit]
Description=High-performance, cost-effective and scalable time series database, long-term remote storage for Prometheus
After=network.target

[Service]
Type=simple
User=victoriametrics
Group=victoriametrics
StartLimitBurst=5
StartLimitInterval=0
Restart=on-failure
RestartSec=1
ExecStart=/usr/local/bin/victoria-metrics-prod \
        -storageDataPath=/var/lib/victoria-metrics-data \
        -httpListenAddr=127.0.0.1:8428 \
        -retentionPeriod=1
ExecStop=/bin/kill -s SIGTERM $MAINPID
LimitNOFILE=65536
LimitNPROC=32000

[Install]
WantedBy=multi-user.target

EOF

At this point your can start the service systemctl enable victoriametrics.service --now, however the port 8428 is not protected in any way nor is encrypted so will add basic authentication and tls encryption with a self sign certificate, any valid certificate will work however. Note that listens only on localhost.

Vmauth

To protect the service will use vmauth which is part of a tool set released by victoria metrics.

# download and install the vm utils

$ curl -L https://github.com/VictoriaMetrics/VictoriaMetrics/releases/download/v1.70.0/vmutils-amd64-v1.70.0.tar.gz --output vmutils-amd64-v1.70.0.tar.gz
$ sudo tar xvf vmutils-amd64-v1.70.0.tar.gz -C /usr/local/bin/
$ chown -v root:root /usr/local/bin/vm*-prod
Configure vmauth

Create a config file (config.yml) to enable basic authentication.

The format of the file is simple, you need a username and a password.

$ sudo mkdir -p /etc/victoriametrics/ssl/
$ sudo chown -vR victoriametrics:victoriametrics /etc/victoriametrics
$ sudo touch /etc/victoriametrics/config.yml
$ sudo chown -v victoriametrics:victoriametrics /etc/victoriametrics/config.yml

# generate a password for our user
$ python3  -c 'import secrets; print(secrets.token_urlsafe())'
KGKK_NoiciEMn6KdBk6CkcLHZt6TpB-Cgt12UFqnutU

# wite the config
$ sudo cat >> /etc/victoriametrics/config.yml <<EOF
> users:
>   - username: "user1"
>     password: "KGKK_NoiciEMn6KdBk6CkcLHZt6TpB-Cgt12UFqnutU"
>     url_prefix: "http://127.0.0.1:8428"
> # end config
> EOF
Install a self sign certificate
$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout /etc/victoriametrics/ssl/victoriametrics.key -out /etc/victoriametrics/ssl/victoriametrics.crt

$ sudo chown -Rv victoriametrics:victoriametrics /etc/victoriametrics/ssl/
Enable vmauth service
cat >> /etc/systemd/system/vmauth.service <<EOF
[Unit]
Description=Simple auth proxy, router and load balancer for VictoriaMetrics
After=network.target

[Service]
Type=simple
User=victoriametrics
Group=victoriametrics
StartLimitBurst=5
StartLimitInterval=0
Restart=on-failure
RestartSec=1
ExecStart=/usr/local/bin/vmauth-prod \
        --tls=true \
        --auth.config=/etc/victoriametrics/config.yml \
        --httpListenAddr=0.0.0.0:8247 \
        --tlsCertFile=/etc/victoriametrics/ssl/victoriametrics.crt \
        --tlsKeyFile=/etc/victoriametrics/ssl/victoriametrics.key \
ExecStop=/bin/kill -s SIGTERM $MAINPID
LimitNOFILE=65536
LimitNPROC=32000

[Install]
WantedBy=multi-user.target


EOF

Start and enable systemctl enable vmauth.service --now .

To test you will need first to construct a base64 string from the username and password you have written into the config.ymlfile.

For example user vmuser and password secret

$ echo -n 'vmuser:secret' | base64
$ dm11c2VyOnNlY3JldA==

# to test vmauth
$ curl -H 'Authorization: Basic dm11c2VyOnNlY3JldA==' --insecure https://localhost:8247/api/v1/query -d 'query={job=~".*"}'

Operations

Snaphots

List what’s available

curl 'https://localhost:8247/snapshot/list'

{"status":"ok","snapshots":["20211227145126-16C1DDB61673BA11"

Create a new snapshot

curl 'https://localhost:8247/snapshot/create'

{"status":"ok","snapshot":"20211227145526-16C1DDB61673BA12"}

List again the snapshots

curl -s 'https://localhost:8247/snapshot/list' | jq .
{
  "status": "ok",
  "snapshots": [
    "20211227145126-16C1DDB61673BA11",
    "20211227145526-16C1DDB61673BA12"
  ]
}

Backups

The snapshots are located on local disk under data path (parameter -storageDataPath=) on my instance it resolves to storageDataPath=/var/lib/victoria-metrics-data/.

The data into snapshots is compressed with Zstandard.

To push the backups to s3 you can use vmbackup.

$ sudo vmbackup-prod -storageDataPath=/var/lib/victoria-metrics-data  -snapshotName=20211227145526-16C1DDB61673BA12 -dst=s3://BUCKET-NAME/`date +%s`

...

2021-12-29T16:07:20.571Z        info    VictoriaMetrics/app/vmbackup/main.go:105        gracefully shutting down http server for metrics at ":8420"
2021-12-29T16:07:20.572Z        info    VictoriaMetrics/app/vmbackup/main.go:109        successfully shut down http server for metrics in 0.001 seconds

For more info you can see vmbackup.

Friday, December 18, 2020

AWS cli filter for security groups

There are times when I want to see the security groups on an AWS region. Nothing special really you can always use the aws cli :)

But wait ... there is so much output especially if you have many groups and many rules.

So this is a simple way to filter on the following values(you can add more values but is mostly what I use)

  • VPC Id
  • Group Name
  • Group Id

Tools that I use

  • aws cli (you need to install it)
  • jq (available on many linux distros)
  • awk (comes with any linux distro)

This is how you put all together

      
      	$ export GROUP='My SG'
        $ aws ec2 describe-security-groups --filters Name=group-name,Values="$GROUP" --output json| jq '.SecurityGroups[]| .VpcId, .GroupName, .GroupId'|  awk '{printf (NR%3==0) ? $0 "\n" : $0}'| sed -e 's/""/ - /g'
        # this will print
        "vpc-xxxxxx - My SG - sg-yyyy"
        # bonus - you can use a regex for GROUP
        $ export GROUP='My*Prod'
        $ aws ec2 describe-security-groups --filters Name=group-name,Values="$GROUP" --output json| jq '.SecurityGroups[]| .VpcId, .GroupName, .GroupId'|  awk '{printf (NR%3==0) ? $0 "\n" : $0}'| sed -e 's/""/ - /g'
        # this will print
        "vpc-xxxxxx - My Prod - sg-yyyy"
        "vpc-xxxxxx - My deprecated Prod - sg-yyyy"
        "vpc-xxxxxx - My whatever Prod - sg-yyyy"
         
      

Tuesday, October 30, 2012

Ec2 (aws) - delete snapshots

Ec2 snapshots are a way to make backups of your data into the amazon cloud. To do snapshots you will need the ec2-api-tools, your access key and secret or the x509 certificates for your aws account. Obviously after you snapshot you will need eventually to delete snapshots that you don't need anymore. This example shows how to use the ec2-api-tools into a shell to delete snapshots that are not part of the current month. You can have a cronjob that runs every last day of the month, this will give you almost 30 days of snapshots.
# describe snapshots and sort by date
ec2-describe-snapshots -C cert.pem  -K key.pem | sort -k 5

# delete all but current month (not the last 30 days)
ec2-describe-snapshots -C cert.pem  -K key.pem | grep -v $(date +%Y-%M-) |  awk '{print $2}' | xargs -n 1 -t ec2-delete-snapshot -K key.pem -C cert.pem